React-Native uses the Fetch API to handle API calls. I’m going to show a few examples of how to handle various API calls.
Get requests are very straightforward using Fetch. You include the url of the API and then handle the response.
First we include the url.
fetch("http://fakewebsite.com/example")
Then we convert our response to JSON data.
.then(exampleResponse => exampleResponse.json())
We’ll want to catch any errors that occur.
.catch((error) => {
console.error('Example error: ', error);
})
Then we assign the response to our components state.
.then(exampleJSON => {
console.log('Example response in JSON format: ', exampleJSON);
this.setState({
paramA: exampleJSON.paramA,
paramB: exampleJSON.paramB
});
});
Here’s the whole enchilada:
fetch("http://fakewebsite.com/example")
.then(exampleResponse => exampleReponse.json())
.catch((error) => {
console.error('Example error: ', error);
})
.then(exampleJSON => {
console.log('Example response in JSON format: ', exampleJSON);
this.setState({
paramA: exampleJSON.paramA,
paramB: exampleJSON.paramB
});
});
Posting to an API using Fetch is similar to Get. We’re still going to have a url. We’ll convert data to JSON format, catch any errors, and then handle the response from the API.
In addition, we’ll have information about our post that we’ll need to send. This is info that the API will need in order to process our request and send us back a response.
First, the url.
fetch("http://fakewebsite.com/example")
Next the information for the API. We’ll include:
{
method: 'POST',
headers: {
"Accept": 'application/json',
"Content-Type": application/json
},
body: JSON.stringify({
paramA: this.state.paramA,
paramB: this.state.paramB
})
}
Then we’ll handle the response - the info that the API sends back to us.
.then(exampleResponse => exampleResponse.json())
We catch any errors.
.catch((error) => {
console.error('Example error: ', error);
})
Then we assign the response to our components state.
.then(exampleJSON => {
console.log('Example response in JSON format: ', exampleJSON);
this.setState({
paramA: exampleJSON.paramA,
paramB: exampleJSON.paramB
});
});
Put it all together and it looks like this:
fetch("http://fakewebsite.com/example", {
method: 'POST',
headers: {
"Accept": 'application/json',
"Content-Type": application/json
},
body: JSON.stringify({
paramA: this.state.paramA,
paramB: this.state.paramB
})
})
.then(exampleResponse => exampleResponse.json())
.catch((error) => {
console.error('Example error: ', error);
})
.then(exampleJSON => {
console.log('Example response in JSON format: ', exampleJSON);
this.setState({
paramA: exampleJSON.paramA,
paramB: exampleJSON.paramB
});
});
In local development your IOS simulator will only work if you make your url point to localhost.
http://localhost:5000
In local development your Android simulator will only work if you give your url an explicit address.
http://10.0.2.2:5000