DEV Community

Cover image for How To Use Axios In React JS
Udemezue John
Udemezue John

Posted on

How To Use Axios In React JS

Introduction.

If you're working with React, handling API requests efficiently is a big deal.

Fetching data from a server, submitting forms, or handling authentication—all these things rely on making HTTP requests. That’s where Axios comes in.

Axios is one of the most popular JavaScript libraries for making HTTP requests.

It’s easy to use, works well with React, and has powerful features like automatic JSON conversion, request cancellation, and error handling.

If you've been struggling with the built-in fetch API or just want a better way to manage API calls, Axios is a great choice.

In this guide, I'll walk you through everything you need to know about using Axios in React, from installation to advanced features like interceptors and error handling.

1. What is Axios?

Axios is a JavaScript library used to send HTTP requests. It’s widely used in React applications because it simplifies API calls and provides built-in features that make development easier.

Why use Axios instead of fetch()?

The built-in fetch() function in JavaScript can also make HTTP requests, but Axios has several advantages:

Automatic JSON conversion – No need to manually convert response data.

Better error handling – Provides detailed error messages.

Request cancellation – Easily cancel API requests when needed.

Supports timeout – Automatically cancels requests that take too long.

Intercept requests & responses – Modify requests before they’re sent.

2. How to Install Axios in React

Before using Axios, you need to install it. If you’re using npm, run:

npm install axios
Enter fullscreen mode Exit fullscreen mode

For yarn, use:

yarn add axios
Enter fullscreen mode Exit fullscreen mode

Once installed, you can start using it in your React components.

3. Making a GET Request with Axios

A GET request is used to fetch data from an API. Here’s how you do it with Axios:

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

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

  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/posts/1")
      .then((response) => {
        setData(response.data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error);
        setLoading(false);
      });
  }, []);

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

  return (
    <div>
      <h2>{data.title}</h2>
      <p>{data.body}</p>
    </div>
  );
};

export default FetchData;
Enter fullscreen mode Exit fullscreen mode

How it Works:

  1. The useEffect hook runs when the component mounts.
  2. Axios sends a GET request to fetch a post.
  3. If successful, it updates the data state.
  4. If there’s an error, it updates the error state.
  5. The component displays the data once loaded.

4. Making a POST Request with Axios

A POST request is used to send data to a server. Here’s how you can do it:

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

const CreatePost = () => {
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const [response, setResponse] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const res = await axios.post("https://jsonplaceholder.typicode.com/posts", {
        title,
        body,
        userId: 1,
      });

      setResponse(res.data);
    } catch (error) {
      console.error("Error creating post:", error);
    }
  };

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

      {response && (
        <div>
          <h3>Post Created:</h3>
          <p>Title: {response.title}</p>
          <p>Body: {response.body}</p>
        </div>
      )}
    </div>
  );
};

export default CreatePost;
Enter fullscreen mode Exit fullscreen mode

How it Works:

  1. The form takes user input.
  2. On submit, Axios sends a POST request.
  3. If successful, it updates the response state.

5. Using Axios Interceptors for Better Request Handling

Interceptors let you modify requests or responses before they reach the client.

Example: Adding an Authorization Token

axios.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `Bearer YOUR_ACCESS_TOKEN`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
Enter fullscreen mode Exit fullscreen mode

This ensures all API requests include an authentication token automatically.

6. Handling Errors with Axios

Axios provides detailed error messages when something goes wrong. Here’s a simple error-handling function:

const fetchData = async () => {
  try {
    const response = await axios.get("https://jsonplaceholder.typicode.com/posts/1");
    console.log(response.data);
  } catch (error) {
    if (error.response) {
      console.log("Server Error:", error.response.status);
    } else if (error.request) {
      console.log("Network Error: No response received");
    } else {
      console.log("Error:", error.message);
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

This helps in debugging different types of API errors.

FAQs

1. Can I use Axios with async/await?

Yes, Axios works perfectly with async/await. It makes the code cleaner and easier to read.

2. How do I cancel an Axios request?

You can use the CancelToken feature to cancel requests:

const source = axios.CancelToken.source();
axios.get("https://jsonplaceholder.typicode.com/posts", { cancelToken: source.token });
source.cancel("Request canceled by the user.");
Enter fullscreen mode Exit fullscreen mode

3. Is Axios better than fetch()?

Yes, Axios is generally better because it has automatic JSON parsing, built-in timeout handling, and better error management.

Further Resources

Conclusion

Axios makes API calls in React much easier. It handles errors better, supports request cancellation, and simplifies working with JSON.

It doesn't matter if you’re making simple GET and POST requests or handling authentication with interceptors, Axios is a great tool to have in your React project.

Have you tried using Axios in React? What challenges have you faced? Let me know in the comments! 🚀

Are you new to tech? Check out the article on how to get started in tech as a beginner to gain more insights

Top comments (0)