A Comprehensive Guide to Using Axios in React

Axios in React

Web apps need APIs at some point during the development stage to fetch data. In the case of React projects, Axios stands out as one of the most efficient libraries to fetch asynchronous data. React development companies effectively leverage this data fetching tool to simplify the process of creating and managing HTTP requests. This blog explores Axios by discussing its features, advantages and working in detail. You can also find a step-by-step guide to using Axios in React for handling different HTTP requests. 

1. What is Axios?

Axios is an open-source, promise-based HTTP client that utilizes JavaScript promises to make HTTP requests and handle their responses. It runs with the same codebase in NodeJS as well as the browser. Axios uses native node.js.http on the server side and XMLHttpRequests on the client side. Axios offers many advanced data fetching APIs unavailable in the basic Fetch API, making it one of the most popular data fetching packages in the NPM.

1.1 Features of Axios in React

Axios is a useful asset of React because it provides the following features: 

  • Automatic JSON Data Handling: Developers don’t have to parse JSON responses manually because Axios has automated the process. This helps you send JSON data in request payloads seamlessly. Axios makes it simple to work with APIs that reduce the boilerplate code and return JSON data. 
  • Built-in CSRF Protection: There is no need to use custom solutions to protect your web app against CSRF attacks because Axios offers built-in CSRF support in the configuration options when setting headers such as X-CSRF-Token. This helps enhance the overall app security. 
  • Error Handling: Axios provides some robust error-handling features. It allows you to intercept HTTP errors and offers customizable mechanisms such as error messages and retry requests to manage them. 
  • Asynchronous Operations: Both React and JavaScript support asynchronous operations. As a result, Axios has the same capabilities that help maintain seamless user interactions by ensuring that network requests don’t block the main thread. 
  • Interceptor Support: Axios allows you to define and handle interceptors for both requests and responses. Interceptors are used for modifying requests and responses before sending them. They also help manage errors globally and enable centralized logic for activities like logging or adding authentication tokens.

1.2 Advantages of Axios in React

Some of the common benefits of using Axios in React include: 

  • Simplified HTTP Requests: Axios supports all types of HTTP methods. It provides a clean and simple API for making various HTTP requests in the React app, such as GET, POST, PUT, DELETE, etc, allowing you to easily interact with RESTful APIs and carry out CRUD operations. 
  • High Configurability: Axios provides a wide range of configuration options, such as timeout settings and custom headers, to help you fulfill diverse application requirements. 
  • Browser and Node.js Compatibility: Axios can work with both NodeJS and browser environments, making it flexible for both client-side and server-side development. Such compatibility also ensures consistency in managing HTTP requests across both environments. 
  • Interoperability: Axios can easily integrate with different types of JavaScript frameworks and libraries. Developers prefer to use it to integrate React apps with backend APIs. 
  • Community Support and Documentation: React has a great community support, and most of the React developers prefer to use Axios because of its large range of offerings. The community also provides online support and detailed documentation to help developers resolve development issues and adhere to best practices.

1.3 Prerequisites For Using Axios in React

Setting up the environment and dependencies takes priority before you get started with Axios in a React application. Here are some common prerequisites: 

  • Node.js and npm/yarn: Make sure that Node.js is installed on your system or device. You will also need either Node Package Manager or its alternative, Yarn, to install Axios and relevant dependencies. 
  • React Setup: Use Create React App or any of your preferred methods to set up a React app. You need to initiate a React project with some essential configurations and folder structures. 
  • Axios Installation: Use npm or yarn to install Axios in your React project.

2. Installing Axios

You can use different tools to install Axios in React, leading to several installation methods.

  1. Using npm:
    $ npm install axios
  2. Using bower:
    $ bower install axios
  3. Using yarn:
    $ yarn add axios
  4. Using jsDelivr CDN:
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  5. Using unpkg CDN:
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

3. Setting Up Axios in a React Application

The first step to setting up Axios in React is to install it, and then we can move on to creating HTTP requests. Use Create React App to start a new project in React. 

Step 1: Installing Axios

Run the command given below in the root directory of your React project to install Axios.

npm install axios

Step 2: Importing Axios

Import axios from ‘axios’ in your React component.

Step 3: Adding Axios as a Dependency

Use the following command to install the Axios library.

npm i axios
Axios library

You take a look at the package.json file to check out the updated dependencies.

"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"
},

4. Handling GET Requests

The below code shows how to use Axios to make a GET request:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
  const [users, setUsers] = useState([]);
  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        setUsers(response.data); // Store user data in state
      })
      .catch(error => {
        console.error('Error fetching users:', error);
      });
  }, []);
 
  return (
    <div style={{ padding: '20px' }}>
      <h1>User List</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            <strong>{user.name}</strong>{user.email}
          </li>
        ))}
      </ul>
    </div>
  );
}
export default App;

Explanation:

  • useState Hook: This hook helps handle the state of your data, which stores the fetched API response. 
  • useEffect Hook: Axios makes the GET request with an empty dependency array([]) inside useEffect to make sure that the hook runs as soon as the component is mounted. It helps perform side effects in the functional component. 
  • Axios GET Request: Make a GET request to any API endpoint utilizing the axios.get. Use chain then() to manage a successful response and catch() to manage errors when Axios returns a promise. 
  • Updating State: Depending on the fetched data, use setData to update the data state 
  • Rendering Data: The fetched data is rendered in the JSX.

5. Posting Data (POST Request)

Run the code given below using Axios to handle the POST request‍.

import React, { useState } from "react";
import axios from "axios";
 
const App = () => {
  const [userData, setUserData] = useState({
    name: "",
    email: "",
  });
 
  const handleChange = (e) => {
    setUserData((prev) => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
 
    try {
      const response = await axios.post(
        "https://api.example.com/users",
        userData
      );
      console.log("User added successfully! Response:", response.data);
      // Optionally clear form or show success
    } catch (error) {
      console.error("Error adding user:", error);
      // Optionally show error to user
    }
  };
  return (
    <div>
      <h1>Add New User</h1>
      <form onSubmit={handleSubmit}>
        <label>Name:</label>
        <br />
        <input
          type="text"
          name="name"
          value={userData.name}
          onChange={handleChange}
        />
        <br />
        <br />
 
        <label>Email:</label>
        <br />
        <input
          type="email"
          name="email"
          value={userData.email}
          onChange={handleChange}
        />
        <br />
        <br />
        <button type="submit">Add User</button>
      </form>
    </div>
  );
};
 
export default App;

Explanation:

  • Handle the formData using the useState hook. 
  • The act of submitting the form calls the handleSubmit function, which triggers an Axios POST request to https://api.example.com/users with formData. 
  • When the user enters the data into the input fields of a form, the handleChange function updates the formData.

6. How to Make a DELETE Request in Axios?

We will be using the DELETE method to delete a post or other resources. The code for this HTTP method is given below. You won’t need a second argument to perform this request.

import React, { useEffect, useState } from "react";
import axios from "axios";
const baseURL = "https://jsonplaceholder.typicode.com/users";
 
export default function App() {
  const [user, setUser] = useState(null);
 
  useEffect(() => {
    // Fetch user with ID 1
    axios.get(`${baseURL}/1`).then((response) => {
      setUser(response.data);
    });
  }, []);
 
  function deleteUser() {
    axios.delete(`${baseURL}/1`).then(() => {
      alert("User deleted successfully!");
      setUser(null);
    });
  }
  if (!user) return <p>No user found.</p>;
  return (
    <div style={{ padding: "20px" }}>
      <h1>{user.name}</h1>
      <p>Email: {user.email}</p>
      <button onClick={deleteUser}>Delete User</button>
    </div>
  );
}

The delete() method returns data, which is not required in most cases. In the above example, we use the then() callback to ensure that the request is resolved successfully. After deleting the user, an alert is sent to the user, notifying them about the success of the delete request. Next, we set the state of the user data to its initial null value to clear it out. The “No User Found” text is displayed after the alert message once the post is deleted.

7. Using Axios to Handle Errors in React

Error handling with Axios allows you to manage API requests in React. Axios offers different types of error management techniques. Here we take an example of the one that uses promises.

import React, { useEffect } from "react";
import axios from "axios";
export default function App() {
  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/users/invalid-id") // invalid endpoint
      .then((response) => {
        // Handle success
        console.log("User data:", response.data);
      })
      .catch((error) => {
        // Handle different error types
        if (error.response) {
          // Server responded with a status outside the 2xx range
          console.error("Error Response Status:", error.response.status);
          console.error("Error Response Data:", error.response.data);
        } else if (error.request) {
          // Request was made but no response received
          console.error("No response received:", error.request);
        } else {
          // Error occurred while setting up the request
          console.error("Error Message:", error.message);
        }
      });
  }, []);
 
  return (
    <div style={{ padding: "20px" }}>
      <h1>Axios Error Handling Example</h1>
      <p>Open the console to view error details.</p>
    </div>
  );
}

Here, we have the “catch()” to handle errors. The code also shows the error object, providing different properties for different scenarios. When the server receives a response, the “error.response” is present in the code. Meanwhile, the “error.request” is present when the request is made, but no response is received. If an error occurs when setting up the request, the “error.message” is present. 

8. Handling Async/Await

We use the async/await syntax with Axios to improve the readability of your JavaScript code. Now, go to your React project, open the Axios folder, and create a new file named asyncAwaitExample.js and add the code below to it.

// Import Axios
import axios from "axios";
// Make an asynchronous request using async/await
const fetchUserAsync = async () => {
  try {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/users/1"
    );
    console.log("User data fetched asynchronously:", response.data);
  } catch (error) {
    console.error("Error fetching user data:", error);
  }
};
// Export the function for use in other files
export default fetchUserAsync;

The above code example shows that we import Axios into the asyncAwaitExample.js file to manage HTTP requests. We use the async/await syntax to define the ‘fetchUserAsync’ function as an asynchronous operation. 

We create a GET request using Axios to a specific URL in the try block. Once the displayed message shows a successful asynchronous retrieval, we must log the fetched data to the console. If there are any errors, they will be caught in the catch block and logged to the console. 

Now, we use async/await to fetch data asynchronously to the App.js component by importing the fetchUserAsync function.

import React, { useEffect } from "react";
import fetchUserAsync from "./fetchUserAsync";
const App = () => {
  useEffect(() => {
    fetchUserAsync();
  }, []);
  return (
    <div>
      <h2>Mastering Axios in React: A Complete Overview</h2>
      <p>Handling Async/Await GET Request (User Info)</p>
    </div>
  );
};
export default App;

Output

Output

9. Using a Base Instance in Axios

In this section, we will learn how to use Axios to set up a base instance to define a URL and other configuration elements. Create a new file called api.js.

nano src/api.js

Use the following defaults to export a new axios.

src/api.js
import axios from 'axios';
// Create a custom Axios instance with a base URL
const API = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com/'
});
export default API;

After setting up the default, we can use it in the PersonRemove component. Use the code below to import a new instance. 

src/components/userFetcher.js
 
import React, { useState } from "react";
import API from "../api";
export default function UserFetcher() {
  const [userId, setUserId] = useState("");
  const [user, setUser] = useState(null);
  const handleFetch = (e) => {
    e.preventDefault();
    if (!userId) return;
    // Use the base instance to make a GET request
    API.get(`users/${userId}`)
      .then((res) => {
        console.log(res.data);
        setUser(res.data);
      })
      .catch((err) => {
        console.error("Error fetching user:", err);
        setUser(null);
      });
  };
  return (
    <div>
      <h2>Fetch User Details</h2>
      <form onSubmit={handleFetch}>
        <input
          type="number"
          placeholder="Enter user ID"
          value={userId}
          onChange={(e) => setUserId(e.target.value)}
        />
        <button type="submit">Fetch User</button>
      </form>
      {user && (
        <div style={{ marginTop: "10px" }}>
          <p>
            <strong>Name:</strong> {user.name}
          </p>
          <p>
            <strong>Email:</strong> {user.email}
          </p>
        </div>
      )}
    </div>
  );
}

There is no need to type the whole URL every time you need to hit a different API endpoint because “http://jsonplaceholder.typicode.com/” is now our base URL.

10. Interceptors

Axios uses interceptors to intercept and modify the HTTP requests and responses. It’s a robust mechanism that can handle the request and response lifecycle. React developers can use it to add custom logic like authentication, error management and logging, before sending requests or after receiving responses. Now, let’s create a separate file called interceptor.js and add the code below to it. 

import axios from "axios";
// Create a custom Axios instance
const axiosInstance = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com",
});
// Request interceptor
axiosInstance.interceptors.request.use(
  (request) => {
    console.log("Request sent:", request);
    // Add custom headers or authentication here if needed
    return request;
  },
  (error) => {
    console.error("Error in request interceptor:", error);
    return Promise.reject(error);
  }
);
// Response interceptor
axiosInstance.interceptors.response.use(
  (response) => {
    console.log("Response received:", response);
    return response;
  },
  (error) => {
    console.error("Error in response interceptor:", error);
    return Promise.reject(error);
  }
);
export default axiosInstance;
exportdefault createInstance;
"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"
},

The interceptor.js file consists of two interceptors: one for managing requests and another for handling responses. The interceptor managing HTTP requests is created with the Axios.interceptors.request.use method and the Axios.interceptors.response.use method is used to create the interceptor that handles HTTP responses.

Developers can use these methods to intercept HTTP requests and responses before they are sent or received by the server, enabling them to modify the data or add custom logic to it. 

Set up the request and response interceptors in the App.js component by importing the interceptor.js.

import React, { useEffect } from "react";
import axiosInstance from "./interceptors";
function App() {
  const fetchUser = async () => {
    try {
      const response = await axiosInstance.get("/users/2");
      console.log("User Data:", response.data);
    } catch (error) {
      console.error("Error fetching user data:", error);
    }
  };
  useEffect(() => {
    fetchUser();
  }, []);
  return (
    <div>
      <h1>Mastering Axios in React: A Complete Overview</h1>
      <h4>Interceptors Example (User Data)</h4>
    </div>
  );
}
export default App;

The fetchUser function from the App.js file allows you to fetch a user from the API endpoint ‘/users/3’ with the help of a custom Axios instance called axiosInstance. Using the custom instance with the useEffect hook ensures that the fetchUser function is called after mounting the component. Once the element is rendered on the screen, the useEffect hook runs the fetchUser function. 

Output

Output

11. Conclusion

Axios is a robust tool that handles HTTP requests in React apps. It supports a variety of features, such as built-in CSRF protection, interceptors, JSON data handling, etc. Using this promise-based API can streamline the API interactions and asynchronous data fetching. 

This tool proves to be reliable for HTTP communication in React projects for its wide range of benefits, including enhanced security, configurability, compatibility, and great community support. This blog explored the ways of managing different HTTP requests using Axios. Feel free to contact our experts if you have any further queries.

profile-image
Parind Shah

Parind Shah is responsible for frontend innovations at TatvaSoft. He brings profound domain experience and a strategic mindset to deliver exceptional user experience. He is always looking to gain and expand his skill set.

Comments

Leave a message...