Open In App

Axios in React: A Guide for Beginners

Last Updated : 21 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

React is one of the most popular JavaScript libraries for building user interfaces, and it works seamlessly with various data-fetching tools. Among these tools, Axios stands out as one of the easiest and most efficient libraries for making HTTP requests in React.

In this article, we’ll explore how to use Axios in a React application, making requests, handling responses, and handling errors.

What is Axios?

Axios is a promise-based HTTP client for JavaScript, which is used to make HTTP requests to fetch or send data to a server. It simplifies the process of handling requests by providing a cleaner API, better error handling, and support for features like request/response interceptors, cancellation, and more. It is also fully compatible with modern browsers and can be used in both the browser and NodeJS environments.

Key Features of Axios

  • Promise-based API.
  • Works in both NodeJS and browsers.
  • Automatically transforms JSON data.
  • Supports request and response interceptors.
  • Allows easy handling of timeouts and cancellation of requests.
  • Supports making GET, POST, PUT, DELETE, and other HTTP requests.

Before you install Axios your React project app should be ready to install this library.

To master React and integrate powerful libraries like Axios seamlessly, check out our comprehensive React course where we cover everything from basics to advanced concepts.

Setting Up Axios in a React Application

Before we start making HTTP requests with Axios, you need to install it. If you’re starting a new React project, create one first using create-react-app (if you haven’t already).

Step 1: Install Axios

To install Axios, run the following command in your React project’s root directory:

npm install axios

Step 2: Import Axios into Your Component

In your React component, import Axios at the top

import axios from 'axios';

Step 3: Add Axios as Dependency

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

Making HTTP Requests with Axios

Let’s start by looking at the two most common HTTP methods you’ll use: GET and POST.

1. GET Request

A GET request is used to retrieve data from an API. Here’s how to use Axios to fetch data from an API endpoint.

import React, { useEffect, useState } from "react";
import axios from "axios";

const App = () => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        // Make GET request to fetch data
        axios
            .get("https://jsonplaceholder.typicode.com/posts")
            .then((response) => {
                setData(response.data);
                setLoading(false);
            })
            .catch((err) => {
                setError(err.message);
                setLoading(false);
            });
    }, []);

    if (loading) return <div>Loading...</div>;
    if (error) return <div>Error: {error}</div>;

    return (
        <div>
            <h1>Posts</h1>
            <ul>
                {data.map((post) => (
                    <li key={post.id}>{post.title}</li>
                ))}
            </ul>
        </div>
    );
};

export default App;
  • State Management: The component uses useState to manage three states: data (stores fetched data), loading (tracks if the data is still loading), and error (handles any error that occurs during the data fetch).
  • Data Fetching with Axios: Inside the useEffect hook, an API request is made using axios.get to fetch posts from the URL https://jsonplaceholder.typicode.com/posts. The response is stored in data, and loading is set to false when the fetch completes.
  • Conditional Rendering: If data is still loading, it displays “Loading…”. If an error occurs, it displays the error message. Otherwise, it renders a list of post titles from the fetched data.

Output

axios-1

GET Request

2. POST Request

POST requests are used to send data to the server. Let’s see how you can use Axios to send data via a POST request.

import React, { useState } from "react";
import axios from "axios";

const CreatePost = () => {
    const [title, setTitle] = useState("");
    const [body, setBody] = useState("");
    const [responseMessage, setResponseMessage] = useState("");

    const handleSubmit = (event) => {
        event.preventDefault();

        const newPost = {
            title,
            body,
        };

        // Make POST request to send data
        axios
            .post("https://jsonplaceholder.typicode.com/posts", newPost)
            .then((response) => {
                setResponseMessage("Post created successfully!");
            })
            .catch((err) => {
                setResponseMessage("Error creating post");
            });
    };

    return (
        <div>
            <h2>Create New Post</h2>
            <form onSubmit={handleSubmit}>
                <input
                    type="text"
                    placeholder="Post Title"
                    value={title}
                    onChange={(e) => setTitle(e.target.value)}
                />
                <textarea
                    placeholder="Post Body"
                    value={body}
                    onChange={(e) => setBody(e.target.value)}
                />
                <button type="submit">Create Post</button>
            </form>
            {responseMessage && <p>{responseMessage}</p>}
        </div>
    );
};

export default CreatePost;
  • State Management: The component uses useState to manage the title, body, and responseMessage states, which store the user input and the response message from the API.
  • Form Handling and POST Request: On form submission (handleSubmit), a new post object is created with the title and body, and a POST request is made using axios.post to send the data to the API.
  • Response Handling: After the request, if successful, a success message is shown (“Post created successfully!”); if there’s an error, it displays an error message (“Error creating post”).

Output

Handling Errors in Axios

Error handling is an important part of working with HTTP requests. In the above examples, we used .catch() to handle any errors that occur during the request. However, Axios provides several ways to manage errors more efficiently:

Error Object: Axios provides an error object containing useful information such as the response status, error message, and more. We can access it like this:

axios
    .get("https://jsonplaceholder.typicode.com/invalid-endpoint")
    .catch((error) => {
        if (error.response) {
            // Server responded with a status other than 2xx
            console.log("Response error:", error.response);
        } else if (error.request) {
            // No response was received
            console.log("Request error:", error.request);
        } else {
            // Something went wrong setting up the request
            console.log("Error:", error.message);
        }
    });

You can use status codes to handle specific error cases, such as redirecting the user if a 401 Unauthorized error occurs, or showing a different message for a 404 Not Found error.

Output

error-handled-

Handling Errors in Axios

Best Practices for Using Axios in React

  • Use Axios with async/await: For cleaner code, consider using async/await with Axios.
const fetchData = async () => {
    try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        setData(response.data);
    } catch (error) {
        setError(error.message);
    }
};
  • Use Axios Instances: For scalability and easier configuration, you can create Axios instances that can be reused across components.
const axiosInstance = axios.create({
    baseURL: "https://jsonplaceholder.typicode.com",
    timeout: 1000,
});

axiosInstance
    .get("/posts")
    .then((response) => {
        console.log(response.data);
    })
    .catch((error) => {
        console.error(error);
    });
  • Handle Loading States: Always handle loading and error states in your UI so users have feedback while waiting for 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. 

Conclusion

Axios is a powerful and easy-to-use HTTP client that simplifies making API requests in React applications. With its built-in features like automatic JSON parsing, request and response interceptors, and error handling, Axios is an excellent choice for handling HTTP requests in your React projects.



Similar Reads

three90RightbarBannerImg