Axios in React: A Guide for Beginners - GeeksforGeeks

29 Apr, 2022
In the tech industry, many frontend frameworks are popular, and React is one of them. With any backend language using this framework is not easy. To communicate with the database developers have to follow a specific rule, and they have to write a certain line of code. 
In React communicating with the backend server is done via HTTP protocol. If you’re a developer, then you might have been familiar with the XML Http Request interface and Fetch API. It allows you to fetch data and make HTTP requests.  
This one is the common method to communicate with the database in React. In React there is another method to communicate with the backend server and that requires the installation of a popular library Axios. 
In this article, we are going to discuss this library, its key features, and how Axios work in different cases while communicating with the database. 
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.
This popular library is used to communicate with the backend. Axios supports the Promise API, native to JS ES6.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. This library is very popular among developers. You can check on GitHub and you will find 78k stars on it. 
This popular library is used to communicate with the backend. Axios supports the Promise API, native to JS ES6.
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. 
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...
Step 1: Below is the command to create React app in your project...npx create-react-app new_files
Step 1: Below is the command to create React app in your project...
npx create-react-app new_files
Step 2: Enter in the directory created in the first step.cd new_files
Step 2: Enter in the directory created in the first step.
cd new_files
Step 3: Install Axios library using the command given below...npm install axios
Step 3: Install Axios library using the command given below...
npm install axios
Step 4: Once this has been done, you can start the server using the command given below..npm start
Step 4: Once this has been done, you can start the server using the command given below..
npm start
After Axios installation, you can import this library into your file and use it to make an HTTP request. Below is the code snippet of a file where the library is imported at the top...
 
Javascript
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;
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, 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  .get("https://jsonplaceholder.typicode.com/customers")  .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
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
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);     })     [Text Wrapping Break]      }    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]])
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.
React-Questions
GBlog
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Introduction to Recurrent Neural Network
12 pip Commands For Python Developers
A Freshers Guide To Programming
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components