waspryo / ip_post_mobile

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React NativeにおけるAPI通信のやり方

fetch(標準のもの)

  • fetchでレスポンスオブジェクトに対して json()関数 で呼ぶ。
componentDidMount() {
      return fetch('http://localhost:5555/api/talent/profile')
        .then((res) => res.json())
        .then((responseJson) => {
          this.setState({
            isLoading: false,
            dataSource: responseJson
          })
          console.log(this.state.dataSource)
        })
        .catch((error) => {
          console.log(error)
        });
    }
  • post
fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue'
  })
});

axios

  • Axiosはdataプロパティ を呼び出す
componentDidMount() {
        axios.get('http://localhost:5555/api/talent/projects')
          .then((responseJson) => {
            this.setState({
              isLoadding: false,
              projects: responseJson.data
            })
            console.log(this.state.projects)
          })
          .catch((err) => {
            console.log(err)
          })
        }

MEMO

  • Fetchの本体は stringified である必要があって、Axiosのデータには object が含まれている
  • axiosはほぼ全てのブラウザに対応している。

スクリーンショット 2020-06-30 23 59 39

About


Languages

Language:JavaScript 100.0%