How is Axios in React used: A Beginner's Guide 2025
Updated on May 12, 2025 | 17 min read | 18.58K+ views
Share:
For working professionals
For fresh graduates
More
Updated on May 12, 2025 | 17 min read | 18.58K+ views
Share:
Table of Contents
Did You Know: NPM download statistics reveal that Axios consistently exceeded 200 million downloads per month last year, highlighting its widespread adoption and strong community support. |
Axios in React is used to make HTTP requests to external APIs or servers. It simplifies handling asynchronous operations with methods like GET, POST, PUT, and DELETE.
Axios also supports features like interceptors for request/response modification, automatic JSON parsing, and error handling, making it a popular choice for managing data fetching in React applications.
In this blog, you'll learn how to set up Axios in React, use it for making requests, and handle errors effectively.
Ready to dive into Axios in React? Sign up for upGrad’s Online Software Development Courses and master HTTP requests, API integration, and more!
Setting up Axios in React project is quick and straightforward. With just a few steps, you can integrate Axios to handle HTTP requests seamlessly in your application.
To set up Axios in React project, follow these steps:
Step 1: Install Axios
Start by installing Axios as a dependency in your project. You can use “npm” or “yarn” for this. Open your terminal and run the following command:
npm install axios
Step 2: Import Axios
In the component where you want to use Axios, import it at the top of your file:
import axios from 'axios';
Step 3: Make API Requests
You can now use Axios to make API requests. For instance, if you want to make a GET request to retrieve data from an API:
axios.get('https://api.example.com/endpoint')
.then(response => {
// Handle the response data
console.log(response.data);
})
.catch(error => {
// Handle any errors
console.error('Error:', error);
});
This code sends a GET request to the URL (https://api.example.com/endpoint). In the “.then()” block, you can access the response data using “response.data”. The “.catch()” block handles any errors during the request.
This setup allows you to easily handle API calls within your React components, making your app ready for data interactions.
Explore these top courses to sharpen your React skills, focusing on essential tools and strategies for building efficient, scalable applications and mastering modern web development.
To make GET requests with Axios in React, use axios.get('URL') inside your component's useEffect or event handler. Once the data is fetched, handle the response using .then() for successful results and .catch() for errors.
Here is an example:
axios.get('https://api.example.com/endpoint')
.then(response => {
console.log(response.data); // Do something with the response data
})
.catch(error => {
console.error('Error:', error); // Handle any errors
});
Output:
If the request is successful and the API responds with data, the response.data will be logged in the console.
{ id: 1, name: 'Sample Item', price: 100 }
If there is an error (e.g., if the endpoint doesn't exist or there's a network issue), the error message will be logged with console.error('Error:', error).
Error: [Error message with details about the issue]
In the above example, we make a GET request to the specified URL (https://api.example.com/endpoint). The “axios.get()” method returns a promise. Hence, we can use “.then()” to handle the successful response. We can use “.catch()” to handle any errors.
After making an API request, you can use the .then() method to handle successful responses and access the returned data. For errors, you can use .catch() to handle any issues that arise.
axios.get('https://api.example.com/endpoint')
.then(response => {
// Handle successful response
console.log(response.data);
})
.catch(error => {
// Handle error
console.error('Error:', error);
});
Output:
{ /* Example output from the server */ }
This will print the data returned from the endpoint.
Error: Error: Network Error
This will print the error message, which could vary depending on the issue encountered. The error object contains detailed information about what went wrong.
In the code above, you handle the response using the “.then()” method. The response data can be accessed through “response.data”. If an error occurs during the request, it can be handled using the “.catch()” method.
When using Axios in React, error handling is an important aspect of handling API requests. Axios provides several ways to handle errors. Here is an example using promises:
axios.get('https://api.example.com/endpoint')
.then(response => {
// Handle successful response
console.log(response.data);
})
.catch(error => {
// Handle error
if (error.response) {
// The request was made and the server responded with a status code outside the range of 2xx
console.error('Status:', error.response.status);
console.error('Data:', error.response.data);
} else if (error.request) {
// The request was made but no response was received
console.error('No response received:', error.request);
} else {
// Something happened in setting up the request that triggered an error
console.error('Error:', error.message);
}
});
Output:
{data: "response data", status: 200, ...}
where the actual data returned from the API will be printed.
Status: <status_code>
Data: <error_data>
If the request was made but no response was received:
No response received: <error.request>
If the error occurred during request setup:
Error: <error.message>
This ensures your application handles both success and error cases effectively.
Code Explanation
The “.catch()” block handles errors in the above code. The error object provides different properties for different scenarios. “error.response” is present when a response was received from the server. “error.request” is present when the request was made but no response was received. “error.message” is present when an error occurred while setting up the request.
Also Read: React Component Lifecycle: What Do You Need To Know
You can make the POST request using the “axios.post()” method. Here is an example:
axios.post('https://api.example.com/endpoint', { data: 'example data' })
.then(response => {
console.log(response.data); // Handle the response data
})
.catch(error => {
console.error('Error:', error); // Handle any errors
});
Output:
1. Successful Response:
{ message: "Data received successfully", status: 200 }
2. Error Response (e.g., 404 Not Found):
Error: { response: { status: 404, data: { message: "Not Found" } } }
3. Network Error:
Error: Error: Network Error
4. Request Error (no response):
Error: { request: {...} }
Code Explanation
In the example above, we make a POST request to the URL (https://api.example.com/endpoint). The second argument to “axios.post()” is the data you want to send in the request body. In this case, we pass an object “{ data: ‘example data’ }”.
The “.then()” block handles the successful response, and you can access the response data using “response.data”. The “.catch()” block handles any errors during the request.
When handling POST request responses with Axios in React, you can use the same techniques in handling GET request responses. Here is an example using promises:
axios.post('https://api.example.com/endpoint', { data: 'example data' })
.then(response => {
// Handle successful response
console.log(response.data);
})
.catch(error => {
// Handle error
console.error('Error:', error);
});
If the server returns a successful response, for example:
{ "message": "Data received successfully", "status": 200 }
The output would be:
{ message: "Data received successfully", status: 200 }
If the server returns an error response (e.g., 404 Not Found or 500 Internal Server Error), for example:
{ "message": "Not Found" }
The output might look like:
Error: { response: { status: 404, data: { message: "Not Found" } } }
If the request is made but there's no response (e.g., if the server is down, or the URL is incorrect), the output might look like:
Error: Error: Network Error
If the server doesn't respond, but the request is made, the output will contain information about the request, like this:
Error: { request: {...} }
This typically happens if there's a timeout or no network connection to the server.
In this code, the “.then()” block handles the successful response, and you can access the response data using “response.data”. If an error occurs during the request, it is caught in the “.catch()” block, where you can handle and log it.
Axios interceptors are a powerful feature in React that allow you to intercept and modify requests and responses globally. They act as middleware, enabling you to add custom logic before a request is sent or after receiving a response. This functionality is particularly useful for centralizing common tasks like adding authentication tokens or handling global error logic.
Here’s how to effectively use Axios interceptors in your React application:
What Are Axios Interceptors?
Interceptors allow you to:
Steps to Use Axios Interceptors in React
1. Import Axios into Your Component
You first need to import Axios in React into your component or set it up globally.
2. Create Request and Response Interceptors
You can now set up request interceptors (to modify the request) and response interceptors (to modify the response).
A. Request Interceptor
A request interceptor allows you to modify the outgoing request configuration. For example, you might want to add an authentication token to every request.
B. Response Interceptor
A response interceptor allows you to modify the response data globally. For example, you can handle common errors (e.g., 401 Unauthorized) or modify the response data before passing it to your app.
3. Eject Interceptors When No Longer Needed
It’s important to clean up interceptors, especially in React components, to prevent memory leaks.
You can eject interceptors using the axios.interceptors.eject() method.
Why Use Axios Interceptors?
Use Cases for Axios Interceptors:
Also Read: 13 Best React Project Ideas & Topics for Beginners 2024
Cancelling Axios requests in React involves using the CancelToken feature provided by Axios.
First, you create a cancel token using “axios.CancelToken.source()”. Then, while making a request, you pass the cancel token as the “cancelToken” property in the request configuration.
You call “cancel()” on the cancel token source to cancel the request. When the request is cancelled, it triggers an error that can be handled in the “.catch()” block. By cancelling requests, you can prevent unnecessary network traffic and handle scenarios where a request is no longer needed, improving the efficiency and responsiveness of your React application.
Here are some Axios best practices for React developers:
These are just a few best practices that React developers adopt. There are several more that you may adopt as a software developer.
Also Read: React JS Architecture: Implementation & Best Practices in 2024
Learning Axios in React streamlines handling HTTP requests, making it easier to integrate APIs and manage data efficiently. By mastering these concepts, you can enhance your React development and handle asynchronous operations with ease.
upGrad offers comprehensive programs that provide hands-on experience with advanced technology and industry experts.
In addition to the courses mentioned above, here are some free courses that can further strengthen your foundation in software engineering.
Feeling uncertain about where to go next in your software development path? Consider availing upGrad’s personalized career counseling. They can guide you in choosing the best path tailored to your goals. You can also visit your nearest upGrad center and start hands-on training today!
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Start your journey with our free Software Development courses and gain the practical skills needed to succeed in the tech world!
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Reference Link:
https://npm-stat.com/charts.html
900 articles published
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources