Open In App

Axios in React: A Guide for Beginners

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In React, backend communication is typically achieved using the HTTP protocol. While many developers are familiar with the XML HTTP request interface and Fetch API for making HTTP requests, there’s another powerful library called Axios that simplifies the process further.

Introduction to Axios:

Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST endpoints. This library is very useful to perform CRUD operations.

  1. This popular library is used to communicate with the backend. Axios supports the Promise API, native to JS ES6.
  2. Using Axios we make API requests in our application. Once the request is made we get the data in Return, and then we use this data in our project. 
  3. This library is very popular among developers. You can check on GitHub and you will find 78k stars on it. 

Before you install Axios your React project app should be ready to install this library. Create a React application following the steps given below…

Steps to Create React Application :

Step 1: Below is the command to create React app in your project…

npx create-react-app myreactapp

Step 2: Enter in the directory created in the first step.

cd myreactapp

Step 3: Install Axios library using the command given below…

npm i axios

Project Structure:

Screenshot-from-2023-10-06-09-44-29

The Updated dependencies in package.json file.

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Example: This code snippet uses axios to make an HTTP request to the backend server.

Javascript




// Filename - App.js
 
import React from "react";
import axios from "axios";
 
class App extends React.Component {
    state = {
        newfiles: null,
    };
 
    handleFile(e) {
        // Getting the files from the input
        let newfiles = e.target.newfiles;
        this.setState({ newfiles });
    }
 
    handleUpload(e) {
        let newfiles = this.state.newfiles;
 
        let formData = new FormData();
 
        // Adding files to the formdata
        formData.append("image", newfiles);
        formData.append("name", "Name");
 
        axios({
            // Endpoint to send files
            url: "http://localhost:8080/files",
            method: "POST",
            headers: {
                // Add any auth token here
                authorization: "your token comes here",
            },
 
            // Attaching the form data
            data: formData,
        })
            // Handle the response from backend here
            .then((res) => {})
 
            // Catch errors if any
            .catch((err) => {});
    }
 
    render() {
        return (
            <div>
                <h1>Select your files</h1>
                <input
                    type="file"
                    // To select multiple files
                    multiple="multiple"
                    onChange={(e) => this.handleFile(e)}
                />
                <button
                    onClick={(e) => this.handleUpload(e)}
                >
                    Send Files
                </button>
            </div>
        );
    }
}
 
export default App;


Steps to Run the Application: Open the terminal and type the following command.  

npm start

Output: Open the browser and our project is shown in the URL http://localhost:3000/

The above example is just a small code description to showcase how to use Axios in your project. We will discuss multiple methods such as GET, POST, and PUT in Axios in the upcoming section.

Need of Axios in React:

As we have discussed that Axios allows you to communicate with the APIs in your React project. The same tasks can also be performed by using AJAX, but Axios provide you more functionality and features and that helps you in building your application quickly. 

Axios is a promise-based library, so you need to implement some promise-based asynchronous HTTP requests. jQuery and AJAX also perform the same job but in React project React handles each and everything in its own virtual DOM, so there is no need to use jQuery at all.     

Below is an example to fetch the customer’s data using Axios…

Javascript




const getCustomersData = () => {
    axios
        .then(data => console.log(data.data))
        .catch(error => console.log(error));
};
getCustomersData();


Now let’s come to the next point and understand how different operations can be performed such as fetching the data or consuming the data using Axios (GET-POST-DELETE).

GET Request with Axios:

Create a component MyBlog and hook it into the component DidMount lifecycle. Import the Axios at the top and fetch the data with Get request.

Javascript




// Filename - App.js
 
import React from "react";
import axios from "axios";
export default class MyList extends React.Component {
    state = {
        blogs: [],
    };
    componentDidMount() {
        axios
            .get(
                `https://jsonplaceholder.typicode.com/posts`
            )
            .then((response) => {
                const posts = response.data;
                this.setState({ posts });
            });
    }
    render() {
        return (
            <ul>
                {this.state.posts.map((post) => {
                    post.title;
                })}
            </ul>
        );
    }
}


Here we are using axios.get (URL) to get a promise that returns a response object. Returned response is assigned to the post’s object. We can also retrieve other information such as status code etc.

POST Request with Axios:

Create a new component AddPost for Post requests. This request will add a post to the post list. 

Javascript




// Filename - App.js
 
import React from "react";
import axios from "axios";
export default class AddPost extends React.Component {
    state = {
        postTitle: "",
    };
    handleChange = (event) => {
        this.setState({ postTitle: event.target.value });
    };
    handleSubmit = (event) => {
        event.preventDefault();
        const post = {
            postName: this.state.postName,
        };
        axios
            .post(
                `https://jsonplaceholder.typicode.com/posts`,
                { post }
            )
            .then((res) => {
                console.log(res);
                console.log(res.data);
            });
    };
    render() {
        return (
            <div>
                <form onSubmit="{this.handleSubmit}">
                    <label>
                        Post Name:
                        <input
                            type="text"
                            name="name"
                            onChange="{this.handleChange}"
                        />
                    </label>
                    <button type="submit">Add</button>
                </form>
            </div>
        );
    }
}


In the above code, we have made an HTTP Post request and added a new post to the database. The onChange event triggers the method handleChange() and updates the request when the API request returns the data successfully.

Delete Request With Axios:

To send the delete request to the server axios.delete is used. You need to specify two parameters while making this request URL and optional config. 

axios.delete(url, { 
data: { foo: "bar" },
headers: { "Authorization": "******" }
});

While sending the delete request you will have to set the request body and headers. Use config.data for this purpose. In the above POST request, modify the code as given below…

Javascript




handleSubmit = event => {
    event.preventDefault();
    axios.delete(
        `https://jsonplaceholder.typicode.com/posts/${this.state.postName}`)
        .then(res => {
            console.log(res);
            console.log(res.data);
        })
}


Response Objects in Axios:

When you send a request to the server, you receive a response object from the server with the properties given below…

  • data: You receive data from the server in payload form. This data is returned in JSON form and parse back into a JavaScript object to you.
  • status: You get the HTTP code returned from the server.
  • statusText: HTTP status message returned by the server.
  • headers: All the headers are sent back by the server.
  • config: original request configuration.
  • request: actual XMLHttpRequest object.

Error Object:

You will get an error object if there will be a problem with the request. Promise will be rejected with an error object with the properties given

  • message: Error message text. 
  • response: Response object (if received). 
  • request: Actual XMLHttpRequest object (when running in a browser). 
  • config: Original request configuration. 

Features of Axios Library

  • JSON data is transformed automatically.
  • It transforms the request and response data.
  • Useful in making HTTP requests from Node.js
  • It makes XMLHttpRequests from the browser.
  • Provide client-side support for protecting against XSRF.
  • Supports promise API.
  • Ability to cancel the request.

Shorthand Methods in Axios:

Below are some shorthand methods of Axios…

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

Conclusion

This article explained everything about Axios library. We have discussed some useful operations such as fetching the data, posting the data, updating the data, or deleting the data in Axios. Once you will start working on React, you will have to use this library to communicate with the database server. So it is important to make a practice of it and understand how things work in Axios.



Last Updated : 11 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads