A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/reactjs/axios-in-react-a-guide-for-beginners/ below:

Axios in React: A Guide for Beginners

Axios in React: A Guide for Beginners

Last Updated : 23 Jul, 2025

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

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

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.

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

Output

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.

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

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:

JavaScript
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

Handling Errors in Axios Best Practices for Using Axios in React JavaScript
const fetchData = async () => {
    try {
        const response = await axios.get('https://jsonplaceholder.typicode.com//posts');
        setData(response.data);
    } catch (error) {
        setError(error.message);
    }
};
JavaScript
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);
    });
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...

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

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.


Axios in React: A Guide for Beginners


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4