React-native API call using Fetch
Fetch
The Fetch API provides a JavaScript interface that can fetch resources asynchronously over the network. It is very similar to the XMLHttpRequest, that is used for the same purpose. But the fetch API is powerful and flexible.
Request Data with Fetch
In React Native, you can request data from an API over the network using the fetch() method.
fetch('https://examples.com/data.json');
We simply pass the URL to the fetch method to make a request.
In addition to the URL, fetch can also take an optional second argument. This is where you can customize the HTTP request.
fetch('https://examples.com/data.json', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
firstParam: 'yourValue'
})
});
In the above code snippet, the first argument to the fetch() method is the URL, followed by the additional second argument. To the request object we have passed properties such as method, headers and body. The method is used to determine if the request is a GET, POST, etc.. The body is a simple getter that exposes the body content in JSON format.
Handle Response from Fetch
Once a request is made to the server, the server gets back with a response. Our React Native app needs to handle this response from the server.
Sending a request and waiting for a response back is asynchronous in nature and and we can wrap the fetch call in React Native within an async-await function as shown below.
const getArticlesFromApi = async () => {
let response = await fetch(
'https://examples.com/data.json'
);
let json = await response.json();
return json.movies;
}
};
Handle Errors
While communicating with APIs over the network, we also need to account for handling any errors that may occur. We can efficiently handle errors and either let the user know that an error has occurred or log them on the console if necessary.
Add a try and catch block to our code snippet to catch any errors thrown.
const getArticlesFromApi = async () => {
try {
let response = await fetch(
'https://examples.com/data.json'
);
let json = await response.json();
return json.movies;
} catch (error) {
console.error(error);
}
};
React Native Example in Fetching Data
We are now going to retrieve data from a json file in a sample React Native project. The content of the json file can be found here: testAPI.json
The file contains a title, description and an array of articles. Each article has an id and title. We want to display the list of articles in our React Native app, along with its id. To do this we can follow the steps summarized below:
Steps to fetch data:
- Pass the URL to the fetch API. The URL will be the same as above that contains the testAPI.json file.
- Next we will parse the response object and extract the json response that is obtained.
- UI will display the data response.
- Catch any errors thrown from the fetch call.
The example is written as an expo snack that you can play with here and you can also run it on an iOS or Android simulator by clicking the code snippet below:
import React, { useEffect, useState } from 'react';
import { FlatList, Text, View } from 'react-native';export default App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
console.log(data);useEffect(() => {
fetch('https://raw.githubusercontent.com/adhithiravi/React-Hooks-Examples/master/testAPI.json')
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);return (<View style={{ flex: 1, padding: 24 }}>
{isLoading ? <Text>Loading...</Text> :
( <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'space-between'}}>
<Text style={{ fontSize: 18, color: 'green', textAlign: 'center'}}>{data.title}</Text>
<Text style={{ fontSize: 14, color: 'green', textAlign: 'center', paddingBottom: 10}}>Articles:</Text>
<FlatList
data={data.articles}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Text>{item.id + '. ' + item.title}</Text>
)}
/>
</View>
)}
</View>
);
};
We are using a functional React component in our example. I want to fetch the data as soon as the component mounts, and the best place to fetch would be in the useEffect hook. I am using two state variables, isLoading and data. The data holds the json response from the API and the isLoading holds the status of the call.
useEffect(() => {
fetch('https://raw.githubusercontent.com/adhithiravi/React-Hooks-Examples/master/testAPI.json')
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
The fetch call is passed the URL, the response is then parsed. The setData is used to to set the state of the data which contains the response json. The data state can be used throughout the component. Errors are then handled. The finally block is executed after the call is complete, and it sets the isLoading state to false.