For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentHow To Use Axios with React?

How To Use Axios with React?

Published
05th Sep, 2023
Views
view count loader
Read it in
10 Mins
In this article
    How To Use Axios with React?

    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.

    What is Axios? (A little bit of history) 

    • Axios is used to communicate with the backend and it also supports the Promise API that is native to JS ES6.  
    • It is a library which is used to make requests to an API, return data from the API, and then do things with that data in our React application. 
    • Axios is a very popular (over 78k stars on Github) HTTP client, which allows us to make HTTP  requests from the browser. 

    Why Do We Need Axios in React? 

    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? 

    • So, while React doesn’t care about DOM manipulation at all, why do we need jQuery for our React app? 
    • Since React is handling each and everything within its own virtual DOM, perhaps we don’t need jQuery at all. 
    • And hence, Axios becomes a lighter-weight/optimized solution to play around with our HTTP requests. 
    • Apart from the above mentioned points, why I personally like AXIOS is because it has a very clean and precise syntax. See  the example code below: 
    • Don't worry if you are not familiar with the code, we will learn that later. 

    Click here to learn more about the usereducer used in React. 

    Using FETCH API:   

    const getPostsData = () => {
      fetch(‘https://jsonplaceholder.typicode.com/posts’)
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.log(error));
      }
    }
     getPostsData();

    Using AXIOS: 

    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.  

    Axios with React: Prerequisites  

    In order to use Axios with React, you’ll need the following: 

    1. Install Node (v 10.7 or above). 

    And if it is already installed, check the version by using 

    npm -v  
    1. 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. 

    Installing Axios 

    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.  

    Fetching and Consuming Data with Axios (GET-POST-DELETE) 

    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. 

    Performing GET Request with Axios 

    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. 

    Performing POST Request with Axios 

    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. 

    Performing POST Request with Axios 

    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 

    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);

    Looking at the response object 

    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: 

    • data: It is the payload returned from the server. By default, Axios expects JSON and will parse this back into a JavaScript object for you. 
    • statusIt is basically the HTTP code returned from the server. 
    • statusText: it refers to the HTTP status message returned by the server. 
    • headers: It contains all the headers sent back by the server. 
    • config: It has the original request configuration. 
    • request: It is the actual XMLHttpRequest object (when it is running in a browser)

    Looking at the error object 

    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: 

    • message: the error message text. 
    • response: the response object (if received) as described in the previous section. 
    • request: the actual XMLHttpRequest object (when running in a browser). 
    • configthe original request configuration. 

    Features of Axios Library as per the Documentation: 

    • 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() 

    • Transform request and response data 
    • Make HTTP requests from Node.js 
    • Make XMLHttpRequests from the browser 
    • Client-side support for protecting against XSRF 
    • Supports the Promise API 
    • Intercept request and response: 

    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. 

    • Has an ability to cancel requests 

    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. 

    MAKING MULTIPLE REQUESTS WITH 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 parallelreturn the response data and will console the created_at object from each of the API responses.  

    Think About Abstraction  

    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 });
      }
     }

    Shorthand Methods in Axios  

    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:  

    • axios.request(config) 
    • axios.get(url[, config]) 
    • axios.delete(url[, config]) 
    • axios.head(url[, config]) 
    • axios.options(url[, config]) 
    • axios.post(url[, data[, config]]) 
    • axios.put(url[, data[, config]]) 
    • axios.patch(url[, data[, config]]) 

    Looking to master Python programming? Join our complete python course and unlock endless possibilities. Start coding like a pro today!

    Some Awesome Facts about Axios  

    Wondering about some cool facts about Axios? Let’s check them out! 

    • For Axios, there is no need for a browser environment. This neat simple library also works on the server-side!  And hence we can use Axios in our Node applications as well. 
    • Apart from fetching or retrieving data, with the help of Axios we can also check the token expiry while requesting data for client-side and server-side. And when the token is already expired we can call an API to get the new token and continue the previous API request.  
    • In Axios, monitoring the upload and download progress is quite simple. How? Just set a callback in the request config as shown below, and enjoy. 
    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!");
     });

    Conclusion

    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.

    Profile

    Bala Krishna Ragala

    Blog Author

    Bala Krishna Ragala, Head of Engineering at upGrad, is a seasoned writer and captivating storyteller. With a background in EdTech, E-commerce, and LXP, he excels in building B2C and B2B products at scale. With over 15 years of experience in the industry, Bala has held key roles as CTO/Co-Founder at O2Labs and Head of Business (Web Technologies) at Zeolearn LLC. His passion for learning, sharing, and teaching is evident through his extensive training and mentoring endeavors, where he has delivered over 80 online and 50+ onsite trainings. Bala's strengths as a trainer lie in his extensive knowledge of software applications, excellent communication skills, and engaging presentation style.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon