Axios is a JavaScript library that we use to send HTTP requests from browsers or Node.js. We can handle these requests more conveniently using Axios as compared to any default fetch API method. It is also more flexible as compared to the default fetch API method.
To install Axios in your React.js project first, you need to install it by running the below command inside your React.js Project.
npm install axios
After running the above command on the terminal, you now have Axios installed inside your React.js Project and now you can import it inside your components and start making HTTP requests using it.
Let’s see some code examples which shows that how you can send some GET, POST, PUT, and DELETE requests using Axios.
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const ExampleComponent = () => {
const [data, setData] = useState([]);
useEffect(() => {
// GET request to fetch all data
axios.get('https://api.example.com/data')
.then(response => {
setData(response.data);
})
.catch(error => {
console.error(error);
});
}, []);
const sendPostRequest = () => {
// POST request to add data
const postData = { title: 'Post Title', body: 'Post Description.' };
axios.post('https://api.example.com/posts', postData)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
};
const sendPutRequest = () => {
// PUT request to update your data
const putData = { title: 'Update Post Title', body: 'Update Post Description.' };
axios.put('https://api.example.com/posts/your_post_id', putData)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
};
const deleteRequest = () => {
// DELETE request
axios.delete('https://api.example.com/posts/your_post_id')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
};
return (
<div>
<button onClick={sendPostRequest}>Create Post</button>
<button onClick={sendPutRequest}>Update Post</button>
<button onClick={deleteRequest}>Delete Post</button>
<ul>
{data.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
};
export default ExampleComponent;
In the above code, we saw that we can easily import Axios and how simply we can use it to send different types of requests. We are using the useEffect hook to make a get request and we can see that we are only calling it once when the app gets loads. sendPostRequest, sendPutRequest, and deleteRequest are the arrow functions that basically represent POST, PUT, and DELETE requests.
Some other features that Axios provides are request cancellation, the ability to track the requests, and features like interceptors. Axios makes it very simple and consistent to make HTTP requests.
Now you must be thinking about the default methods which we use for fetching data from an API, you must be thinking of the advantage of using Axios over the default methods. don’t worry we are covering it in the next sections.
Advantages of Axios over default fetch API method in React.js
Simple syntaxes :
Axios provides very simple syntax to make HTTP requests. We have a chaining mechanism so we can chain multiple methods and that makes it more readable and reduce extra code. On the other hand fetch API methods which we have defaulted in React.js handles promises and response objects manually.
Request cancellation:
If a user using a website and send an HTTP request from any form submitted or by clicking on any button and somehow navigating away from the component then this HTTP request will continue to process.
But this should now happen if we move away from the component then these requests should cancel.
In regular fetch API, we do not have any built-in cancellation support, but if we are using Axios then we can cancel our requests using cancel tokens.
let me show you the code example for request cancellation.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const MyComponent = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const source = axios.CancelToken.source();
axios.get('https://api.example.com/data', { cancelToken: source.token })
.then(response => {
setData(response.data);
setLoading(false);
})
.catch(error => {
if (axios.isCancel(error)) {
console.log('Request canceled:', error.message);
} else {
setError(error);
setLoading(false);
}
});
return () => {
source.cancel('Request canceled by cleanup');
};
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
if (!data) {
return null;
}
return (
<div>
{/* Render your data here */}
</div>
);
};
export default MyComponent;
So in this above code, we are using the useEffect hook, and inside this, we are creating a cancel token using axios.CancelToken.source(). After this, we are sending an async request using Axios by passing the cancel Token inside the cancelToken field.
Now what happen, if the request is successful the we receive the data and this will update our component, if any error occurs then we can check for the cancel request using axios.isCancel(error).
We have a cleanup function in the useEffect hook that we can use to cancel the request if there is a component that got unmounted.
Automatic JSON parsing:
With fetch API we manually use json() method to parse the JSON response. but with Axios, we can automatically parse the response in JSON format.
Simplifies Error Handling
One of the Axios features is, it automatically rejects the promises if the request gets failed. It could be any reason, some network issue, or a server error.
With Axios, we get detailed error information like status codes and error messages.
In contrast, the fetch API only rejects the promise of network errors and requires additional checks for server errors.
Interceptors
We use Axios interceptors for adding authentication headers, logging requests, and handling common errors. The fetch API does not have this support for interceptors.
So now we get the idea of why we should use Axios over regular fetch API methods.
The official line for Learning Axios is https://axios-http.com/docs/intro
If you like this article, please share it with your friends and also comment if you want to ask anything about Axios. Happy Reading 🙂