APIs can make your life a whole lot easier. With an API, you can send requests to other services and get responses without having to build those requests and responses yourself. But building an API isn’t as simple as it sounds. It requires careful planning, testing, and debugging. If you’re building an API for the first time, it can feel like an impossible mountain to climb. That’s where APIs like axios come in. It has a great API and lots of helpful features. Here in this article you’ll understand how to use axios to manage API requests in your React Native app.
What is AXIOS?
Axios is one of the easiest HTTP clients to learn and use. Making an API request is as simple as passing a configuration object to Axios or invoking the appropriate method with the necessary arguments. You will learn the basics of Axios in this section.
Configuring Axios
Type following command on terminal window to install Axios:
NPM Install Axios
How to make requests to an API using Axios
Making a call to an API using Axios, you can pass a configuration object to Axios or invoke a method for the corresponding CRUD operations.
For example, you can make a GET request to the /api/users endpoint in one of the following two ways:
import axios from 'axios';
constbaseUrl = 'https://reqres.in';
// Passing configuration object to axios
axios({
method: 'get',
url: `${baseUrl}/api/users/1`,
}).then((response) => {
console.log("<<<<<< Passing configuration object to axios >>>>>>", response.data.data);
});
// Invoking get method to perform a GET request
axios.get(`${baseUrl}/api/users/1`).then((response) => {
console.log("<<<<<< Invoking get method to perform a GET request >>>>>>", response.data.data);
});
There are several other fields such as baseURL, transformRequest, transformResponse, and headers, among others, which you can include in the configuration object you pass to Axios.
// Passing configuration object to axios
constfetchUserFirst = async () => {
constconfigurationObject = {
method: 'get',
url: `${baseUrl}/api/users/1`,
};
const response = await axios(configurationObject);
console.log("<<<<<< Fetch User First >>>>>>", response.data.data);
};
// Invoking get method to perform a GET request
constfetchUserSecond = async () => {
consturl = `${baseUrl}/api/users/2`;
const response = await axios.get(url);
console.log("<<<<<< Fetch User Second >>>>>>", response.data.data);
};
How to make multiple concurrent API requests using Axios
We can use the Promise.all or Promise.allSettled method of the Promise API with Axios to make multiple concurrent API requests from a React Native application.
constconcurrentRequests = [
axios.get(`${baseUrl}/api/users/1`),
axios.get(`${baseUrl}/api/users/2`),
axios.get(`${baseUrl}/api/users/3`),
];
// Using Promise.all
Promise.all(concurrentRequests)
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
// Using Promise.allSettled
Promise.allSettled(concurrentRequests)
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
How to abort network request in Axios
Axios provides functionality for aborting network requests. A typical use case of this feature in React Native is the cancellation of network requests in the use effect hook when a component is unmounted while data is still in flight.
useEffect(() => {
const source = axios.CancelToken.source();
consturl = `${baseUrl}/api/users/${userId}`;
constfetchUsers = async () => {
try {
const response = await axios.get(url, { cancelToken: source.token });
console.log(response.data);
} catch (error) {
if(axios.isCancel(error)){
console.log('Data fetching cancelled');
}else{
// Handle error
}
}
};
fetchUsers();
return () =>source.cancel("Data fetching cancelled");
}, [userId]);
How to create an instance of Axios
You can also create an instance of Axios with a custom configuration.Axios will merge the configuration object passed while creating the instance with the configuration passed to the instance method:
constaxiosInstance = axios.create({ baseURL: 'https://reqres.in/' });
axiosInstance.get('api/users/1').then((response) => {
console.log(response.data);
});
How to make GET request using Axios in React Native
Make a GET request to the /api/users endpoint to retrieve a user and store the user ID in state as shown in the code snippet below. You can change the user ID inside the onPress event handler attached to the Load User button. Changing the user ID will trigger a GET request to the API inside the useEffect hook.
Read More on Managing API Requests In React Native App