Read it in 10 Mins
While dealing with web applications in React, the most common task is to communicate with backend servers. This is usually done via HTTP protocol. We are all quite familiar with the very common XML Http Request interface and Fetch API, which allows us to fetch data and make HTTP requests. There is another way to communicate with the backend in React. In this article, we will learn about the awesome library known as Axios, some of the key features of Axios that have contributed to its popularity among frontend developers and how to use Axios in React. For more information, check out Full Stack course.
So let’s get started.
Axios allows us to communicate with APIs easily in our React apps. Though this can also be achieved by other methods like fetch or AJAX, Axios can provide a little more functionality that goes a long way with applications that use React.
Axios is a promise-based library used with Node.js and your browser to make asynchronous JavaScript HTTP requests.
When we know we need to implement some promise-based asynchronous HTTP requests in our application, with JavaScript, we usually think of only jQuery’s AJAX or fetch method to get the job done. And while doing so, we are actually going against React!! Did you notice that?
Click here to learn more about the usereducer used in React.
const getPostsData = () => { fetch(‘https://jsonplaceholder.typicode.com/posts’) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error)); } } getPostsData();
const getPostsData = () => { axios .get("https://jsonplaceholder.typicode.com/posts") .then(data => console.log(data.data)) .catch(error => console.log(error)); }; getPostsData();
You might be thinking that there isn’t a very big difference but if we consider a POST or Delete or PUT request you can start observing the benefits of using Axios.
In order to use Axios with React, you’ll need the following:
Install Node (v 10.7 or above).
And if it is already installed, check the version by using
npm -v
A React project setup with Create React App or any React boilerplate
If you want to learn more about Axios library, head up to this link.
Okay, now that we have spent a good amount of time in understanding Axios, let’s turn our attention on how to use Axios with React.
In order to use Axios with React, we need to install Axios. It does not come as a native JavaScript API, so that's why we have to manually import into our project. There are many ways to install Axios. You can pick any of them based on your system environment.
Open up a new terminal window, move to your project’s root directory, and run any of the following commands to add Axios to your project.
Using npm:
$ npm install axios
Using bower package manager:
$ bower install axios
Using yarn:
$ yarn add axios
Using unpkg CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Using jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
It’s not as complicated as you might think it’d be.
Web Applications use HTTP requests, for example, GET, POST and PUT, to communicate with APIs. Axios makes our life simple as it is easy for us now to perform these commands.
In this section, we will learn how to use the Axios to make REST API calls like GET, POST and DELETE in React App. So let’s get started.
Let’s create a new component named My List and hook it into the component DidMount lifecycle as shown below. After that we will fetch data with Get request by importing axios.
Wondering how to begin your web development career? Enroll in Web Design Course syllabus.
Here we are using JSON placeholder API for fetching the dummy list data of users.
import React from 'react'; import axios from 'axios'; export default class MyList extends React.Component { state = { persons: [] } componentDidMount() { axios.get(`https://jsonplaceholder.typicode.com/users`) .then(response => { const users = response.data; this.setState ({users}); }) } render() { return ( < ul > {this.state.users.map (user => {user.name} )} < /ul > ) } }
In the above component named MyList, we have imported Axios first. axios.get(--URL--) is used to get a promise which will return a response object. The received data in response.data is assigned to the user's object.
We can also retrieve other Information like status code and others received with the response.
Now let’s create another component named AddUser for using the POST request which will add a user in the user list. (a.ka. Adding data into database)
import React from 'react'; import axios from 'axios'; export default class AddUser extends React.Component { state = { userName: '', } handleChange = event => { this.setState({ userName: event.target.value }); } handleSubmit = event => { event.preventDefault(); const user = { userName: this.state.userName }; axios.post(`https://jsonplaceholder.typicode.com/users`, { user }) .then(res => { console.log(res); console.log(res.data); })[Text Wrapping Break] } render() { return ( <div> <form onSubmit={this.handleSubmit}> <label> User Name: <input type="text" name="name" onChange={this.handleChange}/> </label> <button type="submit">Add</button> </form> </div> ) } }
In the above example, we have made a HTTP Post request to modify the database, which is a user list and added a new user to the database.
Because we've initialized the state, in handleChange() we have updated the state when the API request returns data successfully.
Finally, the delete method. axios.delete is used to make a Delete request to the server.
axiox.delete accepts two parameters: url and optional config.
axios.delete(url, { data: { foo: "bar" }, headers: { "Authorization": "***" } });
We can use config.data to set the request body and headers as shown in the below snippet.
Consider the same component as above and modify the request as follows:
handleSubmit = event => {
event.preventDefault();
axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.userName}`)
.then(res => {
console.log(res);
console.log(res.data);
})
}
And you are done! — you’ve got a transformed and simplified React app
Sending custom headers with Axios is very simple and straightforward.
It is done by passing an object containing the headers as the last argument.
See the below code reference:
const options = { headers: {'X-Custom-Header': 'value'} }; axios.post('/save', { a: 50 }, options);
When we send a request to server and it is successful, our then() callback will receive a response object which can have the following properties:
And if there’s a problem with the request, the promise will be rejected with an error object containing at least one or few of the following properties:
Automatically transforms for JSON data
Axios is intelligent because it automatically converts a response to JSON, so while using Axios we usually skip the step of converting the response to JSON, unlike we do in Fetch()
HTTP interceptors are used when we need to change HTTP requests from our application to the server. Axios provides a way to intercept HTTP requests. And hence Interceptors provide us the ability to do that without writing any extra code.
It has a built-in feature that provides client-side protection against cross-site request forgery.
In case you want to dig in and learn more about these features, head up to the official documentation of AXIOS.
With Axios we get an ability to make multiple HTTP requests and handle them simultaneously using the axios.all() method. This method takes in an array of arguments and in return we get a single promise object that only resolves when all the arguments passed in the array have been resolved.
Look at the below example, where we are making multiple requests to the GitHub api using the axios.all() method.
axios.all([
axios.get('https://api.github.com/users/defunkt),
axios.get('https://api.github.com/users/evanphx)
])
.then(response => {
console.log('Date created: ', response[0].data.created_at);
console.log('Date created: ', response[1].data.created_at);
});
What will happen in the above code is that it will make simultaneous requests to an array of arguments in parallel, return the response data and will console the created_at object from each of the API responses.
In Axios it’s quite possible to create a base instance where we can drop the URL for our API as shown below:
const api = axios.create({ baseURL: "https://api.github.com/users/evanphx" });
And then simply abstract the URL like shown:
async getPostsData() { const response = await api.get(); try { this.setState({ posts: response.data.posts, isLoading: false }); } catch (error) { this.setState({ error, isLoading: false }); } }
You have already seen that Axios provides an easy-to-use API contract model in a compact package for most of our HTTP communication needs.
Do you know that Axios has some shorthand methods for performing different HTTP requests?
Check them below:
Wondering about some cool facts about Axios? Let’s check them out!
axios({ method: "get", url: "/myFilePath", responseType: "blob", onDownloadProgress: (progressEvent) => { const percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); console.log(percentCompleted) this.setState({ loadingPercent: percentCompleted, }); }, }).then((response) => { alert("We are Ready!"); });
I hope this article has helped you in understanding about Axios and its usage for various features like fetching or retrieving data and handling responses. In this article, we saw several practical examples to check the power of Axios inside a React application to create HTTP requests and handle responses. We also got an idea about why it is a better approach than a normal fetch API. So what are you waiting for? Go ahead and give Axios a try. It will definitely make your life easier.
Avail your free 1:1 mentorship session.