Popular Searches
Popular Course Categories
Popular Courses

Integrating Axios

Integrating Axios

API Integration in React

Integrating Axios in React

Axios is a Promise-based HTTP client used to send requests from a React application to a backend server or external API. It helps developers retrieve data, submit forms, create records, update information, and delete resources. Axios simplifies HTTP communication by providing convenient methods, automatic JSON response handling, request configuration, interceptors, and error-handling features.

Course: JustAcademy React JS Training

Course Demo: Register for React JS Course Demo


1. What Is Axios?

Axios is an external JavaScript library that allows applications to communicate with APIs using HTTP requests. In React, Axios is commonly used to retrieve server data and display it through components.

Common Uses of Axios

  • Fetching users, products, posts, and other API data.
  • Submitting login and registration forms.
  • Creating new records through POST requests.
  • Updating existing records through PUT or PATCH requests.
  • Deleting records through DELETE requests.
  • Sending authentication tokens and custom headers.
  • Managing common request and response behavior with interceptors.

2. Why Use Axios in React?

React does not include Axios by default. It can be installed separately and used inside React components, custom Hooks, or API service files.

Feature Benefit
Simple HTTP methods Use methods such as axios.get(), axios.post(), and axios.delete().
Automatic JSON handling JSON response data is generally available through response.data.
Error handling HTTP error responses are rejected by default, allowing handling with catch.
Interceptors Apply shared logic to requests and responses.
Request configuration Configure headers, timeouts, parameters, and other request options.
Request cancellation Cancel supported requests using AbortController.

3. Installing Axios in a React Project

Before using Axios, install it in your React project.

Using npm

npm install axios

Using Yarn

yarn add axios

Using pnpm

pnpm add axios

After installation, import Axios wherever you need to make API requests.

import axios from "axios";

4. Basic Axios Syntax

Axios provides methods for making different types of HTTP requests.

axios.get(url)
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Common Axios Methods

Method Purpose Example
GET Retrieve data axios.get(url)
POST Create or submit data axios.post(url, data)
PUT Replace a resource axios.put(url, data)
PATCH Partially update a resource axios.patch(url, data)
DELETE Request resource deletion axios.delete(url)

5. Fetching Data Using Axios in React

The useEffect Hook can be used to retrieve data when a component is displayed or when its dependencies change. The useState Hook stores the response and request status.

Example: Fetch Users

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

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const controller = new AbortController();

    async function fetchUsers() {
      try {
        setLoading(true);
        setError("");

        const response = await axios.get(
          "https://jsonplaceholder.typicode.com/users",
          { signal: controller.signal }
        );

        setUsers(response.data);
      } catch (err) {
        if (!controller.signal.aborted) {
          setError(
            err.response?.data?.message ||
            err.message ||
            "Failed to fetch users"
          );
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    fetchUsers();

    return () => controller.abort();
  }, []);

  if (loading) {
    return <p>Loading users...</p>;
  }

  if (error) {
    return <p>Error: {error}</p>;
  }

  if (users.length === 0) {
    return <p>No users found.</p>;
  }

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            <strong>{user.name}</strong>
            <p>Email: {user.email}</p>
            <p>City: {user.address.city}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default UserList;

Explanation

  • useState([]) stores the user records.
  • loading indicates that the request is in progress.
  • error stores an error message.
  • useEffect() starts the request after the component commits.
  • axios.get() sends the GET request.
  • response.data contains the parsed response data.
  • setUsers(response.data) updates the component state.
  • AbortController allows the request to be cancelled during cleanup.
  • users.map() renders each user as a list item.

6. Understanding the Axios Response Object

Axios returns a response object containing information about the request and the server response.

Property Description
response.data The data returned by the server.
response.status The HTTP status code, such as 200 or 404.
response.statusText The HTTP status message, when provided.
response.headers The response headers.
response.config The configuration used for the request.
response.request The underlying request object, where available.

Unlike the Fetch API, Axios normally parses JSON responses automatically. You usually do not need to call a separate response.json() method.

7. Using async and await with Axios

The async and await keywords make asynchronous Axios requests easier to read. Combine them with try...catch to handle errors.

import axios from "axios";

async function getPosts() {
  try {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/posts"
    );

    console.log(response.data);
  } catch (error) {
    console.error("Error fetching posts:", error.message);
  }
}

getPosts();

Advantages

  • Improves code readability.
  • Makes sequential asynchronous operations easier to follow.
  • Allows request failures to be handled with try...catch.
  • Works well with React state updates.

8. Sending Data with Axios POST

The POST method is commonly used to submit form information or create a new record on a server.

import axios from "axios";

async function createPost() {
  try {
    const response = await axios.post(
      "https://jsonplaceholder.typicode.com/posts",
      {
        title: "Learning React",
        body: "Practising Axios integration",
        userId: 1
      }
    );

    console.log("Created post:", response.data);
  } catch (error) {
    console.error("Unable to create post:", error.message);
  }
}

createPost();

Important Concepts

  • axios.post() accepts the URL and request data.
  • Axios generally serializes a plain JavaScript object as JSON.
  • Axios sets an appropriate content type for ordinary JSON request bodies.
  • The server decides whether to accept and store the submitted information.

The JSONPlaceholder API is a demonstration service. Its write requests simulate changes rather than permanently saving records in a real database.

9. Updating Data with PUT and PATCH

Use PUT when the API expects a replacement representation of a resource. Use PATCH when the API supports updating selected fields.

PUT Example

async function replacePost() {
  try {
    const response = await axios.put(
      "https://jsonplaceholder.typicode.com/posts/1",
      {
        id: 1,
        title: "Updated Title",
        body: "Updated post content",
        userId: 1
      }
    );

    console.log(response.data);
  } catch (error) {
    console.error("Update failed:", error.message);
  }
}

PATCH Example

async function updatePostTitle() {
  try {
    const response = await axios.patch(
      "https://jsonplaceholder.typicode.com/posts/1",
      { title: "New Post Title" }
    );

    console.log(response.data);
  } catch (error) {
    console.error("Patch failed:", error.message);
  }
}

10. Deleting Data with Axios

The DELETE method sends a request asking the server to delete a specified resource.

async function deletePost() {
  try {
    const response = await axios.delete(
      "https://jsonplaceholder.typicode.com/posts/1"
    );

    console.log("Delete request completed:", response.status);
  } catch (error) {
    console.error("Delete failed:", error.message);
  }
}

Not every successful DELETE response contains JSON data. Some APIs return a 204 No Content response, so check the status or other response information rather than assuming response.data contains a record.

11. Handling Errors in Axios

Axios rejects a request Promise by default when the server responds with an HTTP status outside its configured successful status range. It also reports network failures and other request errors through the rejected Promise.

Example: Detailed Error Handling

import axios from "axios";

async function loadData() {
  try {
    const response = await axios.get("/api/users");
    return response.data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      if (error.response) {
        console.error(
          "Server error:",
          error.response.status
        );
      } else if (error.request) {
        console.error("No response received from server");
      } else {
        console.error("Request setup error:", error.message);
      }
    } else {
      console.error("Unexpected error:", error);
    }

    throw error;
  }
}

Common Error Categories

  • Server response error: The server responded with an unsuccessful HTTP status.
  • Network or no-response error: The request was made, but no readable response was received.
  • Request setup error: An error occurred while configuring or preparing the request.
  • Cancellation: The request was intentionally cancelled.

For production applications, show a helpful user-facing message and keep technical debugging details in appropriate development logs. Avoid exposing sensitive server information to end users.

12. Using Axios with Query Parameters

Query parameters pass additional values in a URL, often for filtering, searching, pagination, or selecting a specific group of records.

async function getPostsByUser() {
  try {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/posts",
      {
        params: {
          userId: 1
        }
      }
    );

    console.log(response.data);
  } catch (error) {
    console.error(error.message);
  }
}

The params option automatically builds the query string. For example, the request includes ?userId=1.

13. Setting Headers and Authentication

Some APIs require request headers to specify the expected content type or provide authentication credentials.

async function getProfile(token) {
  const response = await axios.get(
    "https://api.example.com/profile",
    {
      headers: {
        Authorization: `Bearer ${token}`,
        Accept: "application/json"
      }
    }
  );

  return response.data;
}

This is an illustrative example. Replace the endpoint and authentication method with those required by your API. Never embed private API secrets in frontend code, because users can inspect code delivered to the browser.

14. Creating an Axios Instance

An Axios instance lets you define shared configuration for requests, such as a base URL and timeout. This helps keep API calls consistent across an application.

Create an API Service File

Create a file named src/api/axiosInstance.js.

import axios from "axios";

const api = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com",
  timeout: 10000,
  headers: {
    Accept: "application/json"
  }
});

export default api;

Use the Instance in a Component

import { useEffect, useState } from "react";
import api from "./api/axiosInstance";

function PostList() {
  const [posts, setPosts] = useState([]);
  const [error, setError] = useState("");

  useEffect(() => {
    async function loadPosts() {
      try {
        const response = await api.get("/posts");
        setPosts(response.data);
      } catch (err) {
        setError("Unable to load posts");
      }
    }

    loadPosts();
  }, []);

  if (error) return <p>{error}</p>;

  return (
    <ul>
      {posts.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

export default PostList;

Benefits of Axios Instances

  • Centralizes the API base URL.
  • Allows shared timeout and header configuration.
  • Provides a place to configure interceptors.
  • Reduces repeated configuration across components.
  • Makes API service code easier to maintain.

15. Understanding Axios Interceptors

Interceptors allow you to run shared logic before a request is sent or before a response is passed to the application. They are useful for logging, attaching authentication headers, and handling common response behavior.

15.1 Request Interceptor

A request interceptor can modify the request configuration before the request is sent.

api.interceptors.request.use(
  config => {
    console.log("Sending request:", config.url);
    return config;
  },
  error => Promise.reject(error)
);

15.2 Response Interceptor

A response interceptor can inspect or transform successful responses and handle rejected responses centrally.

api.interceptors.response.use(
  response => response,
  error => {
    console.error("API request failed:", error.message);
    return Promise.reject(error);
  }
);

Example: Add an Authentication Token

api.interceptors.request.use(
  config => {
    const token = getTokenFromYourAuthSystem();

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  error => Promise.reject(error)
);

getTokenFromYourAuthSystem() is a placeholder for a function supplied by your application's authentication system; it is not a built-in Axios function. Use a secure token-management approach appropriate to your application.

Important: Configure interceptors in a shared API setup file rather than repeatedly registering them during component renders. If an interceptor is registered dynamically, remove it when it is no longer needed to avoid duplicate processing.

16. Cancelling Axios Requests

Axios supports AbortController for cancelling requests. Cancellation is helpful when a component is removed or when a new request makes an older request unnecessary.

import axios from "axios";

const controller = new AbortController();

axios.get("/api/users", {
  signal: controller.signal
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (axios.isCancel(error) || error.code === "ERR_CANCELED") {
      console.log("Request cancelled");
    } else {
      console.error(error.message);
    }
  });

// Cancel when appropriate
controller.abort();

When using Axios inside a React Effect, create the controller within the Effect and abort it in the cleanup function when appropriate.

17. Axios vs Fetch API

Both Axios and Fetch can communicate with APIs. The best choice depends on your project's requirements.

Feature Axios Fetch API
Installation Requires installing a package. Built into modern browsers.
JSON response Usually available as response.data. Requires calling response.json().
HTTP error handling Rejects the Promise for unsuccessful HTTP statuses by default. Requires checking response.ok.
Interceptors Provides request and response interceptors. No built-in Axios-style interceptor system.
Timeout configuration Supports a request timeout option. Can use cancellation signals and other mechanisms to implement time limits.
Cancellation Supports AbortController. Supports AbortController.
Best suited for Applications that benefit from shared configuration and HTTP-client features. Simple requests without an additional dependency.

18. Common Axios Mistakes

Mistake Solution
Using response.json() with Axios. Use response.data for a typical JSON response.
Ignoring request errors. Use try...catch or a Promise rejection handler.
Not setting a timeout. Configure an appropriate timeout for requests that should not wait indefinitely.
Repeatedly registering interceptors. Register shared interceptors once in a common API setup.
Using the wrong base URL. Check the API configuration and endpoint paths.
Displaying a blank screen while loading. Manage and render loading state.
Exposing credentials in frontend code. Keep private secrets on a secure server.
Updating state from obsolete requests. Cancel outdated requests or ignore their results.

19. Best Practices for Axios Integration

  • Install Axios using your project's package manager.
  • Create a reusable Axios instance for shared configuration.
  • Keep API calls in service modules when that improves organization.
  • Use async/await and handle errors consistently.
  • Show loading, error, empty, and success states.
  • Configure reasonable request timeouts.
  • Use interceptors only when shared request or response behavior is needed.
  • Cancel obsolete requests where appropriate.
  • Keep authentication and API credentials secure.
  • Use environment configuration for public API base URLs where appropriate; remember that frontend environment variables are not secret.
  • Test successful responses, HTTP errors, network failures, and cancellation.

20. Practical Project: Product Listing Application

Project objective: Build a React application that retrieves products using Axios and displays them in a list or grid.

Project Requirements

  1. Create a React component named ProductList.
  2. Fetch products from https://dummyjson.com/products.
  3. Store the product list in React state.
  4. Show a loading message while data is being retrieved.
  5. Display an error message if the request fails.
  6. Render each product's title, price, and thumbnail.
  7. Use the product ID as the list key.
  8. Add a search field to filter products by title.
  9. Add a retry button when loading fails.

Expected Output

Product Listing
--------------------------------
Search products: [______________]

Product: Smartphone
Price: $499
[Product Image]

Product: Laptop
Price: $899
[Product Image]

The output above is illustrative. The actual product information should come from the API response.

21. Interview Questions and Answers

Q1. What is Axios?

Axios is a Promise-based HTTP client used to send network requests from browser applications and supported server-side JavaScript environments.

Q2. How do you install Axios in React?

Run npm install axios in your React project's terminal.

Q3. How do you make a GET request?

Use axios.get(url) and process the response, usually reading its data from response.data.

Q4. How do you send data with POST?

Use axios.post(url, data), where data contains the information to submit.

Q5. What is the purpose of response.data?

It contains the response body data returned by the server.

Q6. What are Axios interceptors?

Interceptors execute shared logic before requests or before responses are passed to the application.

Q7. How does Axios handle HTTP errors?

By default, Axios rejects the Promise for HTTP statuses outside its configured successful range. The error can be handled using catch or try...catch.

Q8. What is an Axios instance?

An Axios instance is a reusable client created with axios.create() and configured with options such as a base URL and timeout.

Q9. Can Axios cancel a request?

Yes. Axios supports cancellation through AbortController and an associated signal.

Q10. What is the difference between Axios and Fetch?

Axios is an external library with features such as interceptors and convenient JSON handling. Fetch is built into modern browsers but requires explicit HTTP status checks and response-body parsing for common JSON requests.

22. Practice Exercises

  • Install Axios and fetch a list of users.
  • Display posts with loading and error states.
  • Create a new post using a POST request.
  • Update a record using PUT and PATCH.
  • Send a DELETE request to a demonstration API.
  • Create a reusable Axios instance with a base URL and timeout.
  • Add a request interceptor for logging.
  • Implement an authentication header using your application's token system.
  • Cancel an Axios request when the component is removed.
  • Compare the same API request implemented using Axios and Fetch.

23. Official Documentation and Learning Resources

Conclusion

Integrating Axios into React makes API communication convenient and organized. By learning how to install Axios, make HTTP requests, manage response data, handle errors, create reusable instances, configure interceptors, and cancel unnecessary requests, you can build more reliable React applications.

Learn more through JustAcademy React JS Training or Register for React JS Course Demo.

Previous Next
whatsapp