React NativeにおけるAPI通信のやり方
- 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は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)
})
}
- Fetchの本体は stringified である必要があって、Axiosのデータには object が含まれている
- axiosはほぼ全てのブラウザに対応している。