Published: 28 Feb 2025 | Reading Time: 6 min read
In web development, fetching data from an API is essential for any React application. Axios is one of the popular JavaScript libraries used to simplify requests and make HTTP requests from within React components. It simplifies dealing with APIs in React by abstracting out the complexity and ease of use when managing requests and responses. This article will explore integrating axios in react.js, managing API calls, and handling errors in your React application.
Axios is a promise-based HTTP client for the browser, and Node.js allows you to send HTTP requests to communicate with an API. It is lightweight, easy to use, and supports most standard HTTP methods such as GET, POST, PUT, and DELETE. Its popularity derives from flexibility, in-built error handling, and simplicity of use.
Here are the key features of axios react.js:
Here are the reasons why Axios is required in React:
To use react axios, you need to follow these steps:
The installation methods for Axios using various package managers and CDNs:
To use Axios via jsDelivr CDN, include the following script tag in your HTML file:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
This will load Axios into your browser, and you can use it directly in your JavaScript code.
To use Axios via unpkg CDN, include this script tag in your HTML file:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
This will also load Axios; you can use it directly in your JavaScript code.
If you're using Node.js, you can install Axios using npm:
npm install axios
Once installed, you can import Axios in your JavaScript file:
const axios = require('axios');
If you're using Yarn, you can install Axios with the following command:
yarn add axios
Once installed, you can import Axios in your JavaScript file:
import axios from 'axios';
If you're using Bower for front-end package management, you can install Axios using:
bower install axios --save
This will add Axios to your bower_components directory, and you can include it in your HTML file:
<script src="bower_components/axios/dist/axios.min.js"></script>
To begin, create a new React project in your desired folder. Use the following command to initialise a new React app:
npx create-react-app myreactapp
This command will create a new directory called myreactapp and set up all the necessary files for a React project.
Once the project is initialised, navigate to the project directory. You can do this by running the following command:
cd myreactapp
This will take you to the root folder of your React project, where all the files and dependencies are located.
Axios is an external library used for making HTTP requests and must be installed in your project. To install Axios, run the following command:
npm install axios
This will install the Axios library and add it to your node_modules folder and the dependencies section in your 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"
}
Now, Axios is available for use within your React project.
After setting up Axios, you can integrate it into your React components to make API calls. Here's an example of how you might use Axios to upload files to a backend server.
// Filename - App.js
import React from "react";
import axios from "axios";
class App extends React.Component {
state = {
selectedFiles: null, // Stores the selected files for upload
};
// Handles the file selection
handleFileSelection(e) {
const selectedFiles = e.target.files;
this.setState({ selectedFiles });
}
// Handles file upload via POST request
handleFileUpload(e) {
const { selectedFiles } = this.state;
let formData = new FormData();
// Appending the selected files to the form data object
Array.from(selectedFiles).forEach(file => {
formData.append("image", file);
});
formData.append("name", "User's File");
// Axios POST request to upload the files
axios({
url: "http://localhost:8080/upload", // API endpoint
method: "POST",
headers: {
// Optional: Add authorization token if needed
"Authorization": "Bearer your_token_here",
},
data: formData, // Sending form data with the request
})
.then((response) => {
console.log("Files uploaded successfully:", response.data);
})
.catch((error) => {
console.error("Error uploading files:", error);
});
}
render() {
return (
<div>
<h1>Upload Your Files</h1>
<input
type="file"
multiple // Allowing multiple file selection
onChange={(e) => this.handleFileSelection(e)} // Handle file selection
/>
<button onClick={(e) => this.handleFileUpload(e)}>
Upload Files
</button>
</div>
);
}
}
export default App;
In the above program, users of the React component may choose multiple files to be stored in the state using the input field. Then, clicking on the upload files button sends them via an Axios POST request to a backend server using FormData. The server will log the response and, if errors arise, will catch and log them.
After implementing Axios in your project, run the application with the following command:
npm start
This will start the development server, and you can view the application in your browser by navigating to:
http://localhost:3000/
You will see the file upload interface, and once the user selects files and clicks the upload button, the files will be sent to the backend API.
When working with Axios in React, you'll typically make API calls using hooks like useEffect for functional components.
To make an API request and retrieve data, you can use the GET method in Axios.
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data); // Handle the API data
})
.catch(error => {
console.error('Error fetching data:', error); // Handle errors
});
This is a basic API call in React.js, which uses Axios. It could be the URL of the endpoint of any API from which you want to retrieve data.
On Success:
// Assuming response contains this JSON data
{ "id": 1, "name": "Resource" }
Console Output:
{ "id": 1, "name": "Resource" }
On Error:
Error fetching data: [error details]
Sending data to an API can be accomplished using Axios with the POST Method. This is an example of how to implement the axios post method in in react.js:
axios.post('https://api.example.com/submit', {
data: 'example data'
})
.then(response => {
console.log(response.data); // Handle the response data
})
.catch(error => {
console.error('Error submitting data:', error); // Handle errors
});
A POST request sends data (e.g., { data: 'example data' }) to the API. The server's response is captured in response.data, while errors are handled in the catch block.
On Success:
// Example of successful response:
{ "status": "success", "message": "Data submitted successfully" }
Console Output:
{ "status": "success", "message": "Data submitted successfully" }
On Error:
Error submitting data: [error details]
Here are the key differences for GET and POST methods such as:
| Criteria | GET | POST |
|---|---|---|
| Use cases | Retrieving data (for example, search, navigation) | Submitting data (for example, form submissions, file uploads) |
| Idempotent | Yes (repeated requests yield the same result) | No (repeated requests may have different results) |
| Caching | Can be cached, stored in browser history | Can never be cached |
| Data transfer | Information sent through URL (the query string) | Information sent through the request body |
| Purpose | Retrieve/read data | Create/update data |
| Length of data | Limited by URL length restrictions | Very few restrictions |
| Browser display | Data is in the browser history | Data is not in the browser history |
| Use in URLs | Can be bookmarked and included in links | Cannot be bookmarked, no URL-based |
| Error handling | Error is shown in the URL | The server usually handles errors |
| Performance | Faster during data retrieval | A bit slow during large data submission |
The PUT request is typically used for updating existing resources on the server.
const axios = require('axios');
axios.put('https://api.example.com/resource/1', {
data: {
name: 'Updated Resource',
description: 'This is an updated resource.'
}
})
.then(response => {
console.log('Updated resource:', response.data);
})
.catch(error => {
console.error('Error updating resource:', error);
});
In the PUT request, we provide the resource ID in the URL and the new data in the body.
If the PUT request is successful, you'll see the updated resource data printed in the console:
Updated resource: { "id": 1, "name": "Updated Resource", "description": "This is an updated resource." }
If an error occurs, such as the resource not being found or a network issue, you'll see an error message:
Error updating resource: Error: Request failed with status code 40
The DELETE request is used to delete an existing resource on the server.
const axios = require('axios');
axios.delete('https://api.example.com/resource/1')
.then(response => {
console.log('Deleted resource:', response.data);
})
.catch(error => {
console.error('Error deleting resource:', error);
});
In the DELETE request, we provide the resource ID in the URL to specify which resource to delete.
If the DELETE request is successful, you will see a confirmation of the deleted resource:
Deleted resource: { "message": "Resource deleted successfully" }
If the resource doesn't exist or there's a network issue, you will see an error message:
Error deleting resource: Error: Request failed with status code 404
Instead of chaining .then() and .catch(), use async/await for cleaner, more readable code. This approach makes it easier to handle asynchronous logic.
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/endpoint');
console.log(response.data);
} catch (error) {
console.error('Error:', error);
}
};
Using await axios.get() waits for the response from the API request before continuing execution. Try/catch handles success and errors using .then() and .catch().
If the request is successful, you'll see the data from the API:
{ "id": 1, "name": "Resource", "description": "This is a resource." }
If there's an error (e.g., network issue), you'll see:
Error: Error: Request failed with status code 404
Let's understand how Axios simplifies managing successful and failed requests in a React application such as:
When a promise is made within an API using Axios, the code inside .then() is activated in response to the promise. There are three types of useful information contained in the response: status, data, and headers, for example:
axios.get('https://api.example.com/data')
.then(response => {
console.log('Data:', response.data);
console.log('Status:', response.status);
})
.catch(error => {
console.error('Error:', error);
});
Axios offers a versatile way to handle errors. In the event of an error occurring during an API request, the error object provides several properties to help you diagnose the issue:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
console.error('Error response:', error.response);
} else if (error.request) {
console.error('No response received:', error.request);
} else {
console.error('Error:', error.message);
}
});
The response.data holds the API's returned data while response.status provides the HTTP status code (e.g., 200 for success). The catch block handles errors like network issues or timeouts, ensuring proper error logging.
On success, you'll get the response data and status:
Data: { "id": 1, "name": "Resource" }
Status: 200
On error, you can handle different types of errors:
Error: Error: Request failed with status code 500
In React, functional components integrate Axios to make an API call; you can just use the use effect hook to fetch data once it's mounted.
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const FetchData = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => {
setData(response.data); // Set data to state
})
.catch(error => {
setError(error.message); // Handle errors
});
}, []);
return (
<div>
{error ? <p>Error: {error}</p> : <pre>{JSON.stringify(data, null, 2)}</pre>}
</div>
);
};
export default FetchData;
This is an example of making an API call in React.js using Axios in a functional component with state management for the response and errors.
On success, the fetched data is displayed as JSON:
{
"id": 1,
"name": "Resource"
}
On error, an error message is shown:
Error: Error: Request failed with status code 404
You can configure Axios to set global defaults such as base URLs, headers, and timeouts. You can also make similar requests multiple times more easily.
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000, // Set timeout for requests
headers: { 'Authorization': 'Bearer token' }
});
export default axiosInstance;
This Axios example in React can now be used across different components. This can be used for API calls in various parts of the app.
Axios requests made with this instance will automatically use the base URL and header:
axiosInstance.get('/data')
.then(response => {
console.log(response.data);
});
You can use Axios interceptors to modify requests and responses globally before handling .then() or .catch(). This is particularly useful for authentication token handling, adding headers, or logging.
axios.interceptors.request.use(request => {
request.headers['Authorization'] = 'Bearer token'; // Add authorization header
return request;
}, error => {
return Promise.reject(error);
});
This interceptor adds an Authorization header with a Bearer token to every outgoing request. If an error occurs during request preparation, it's rejected with Promise.reject.
For requests, every request will now include the Authorization header.
axios.interceptors.response.use(response => {
// Process the response before passing it to the .then() handler
return response;
}, error => {
// Handle errors globally
console.error('Global error handler:', error);
return Promise.reject(error);
});
The response interceptor allows the processing of the response before it reaches .then(). If an error occurs during the response, it logs globally and rejects the promise with Promise.reject.
For responses, errors will be globally logged, and you can modify or reject responses.
In cases where a request is no longer needed (e.g., a user navigates to another page before a request completes), you can cancel ongoing requests to avoid unnecessary network traffic. Axios supports request cancellation using a CancelToken.
const cancelTokenSource = axios.CancelToken.source();
axios.get('https://api.example.com/endpoint', {
cancelToken: cancelTokenSource.token
})
.then(response => {
console.log(response.data);
})
.catch(error => {
if (axios.isCancel(error)) {
console.log('Request canceled', error.message);
} else {
console.error(error);
}
});
// To cancel the request:
cancelTokenSource.cancel('Request cancelled by the user.');
This code describes how to cancel an Axios request. It creates a CancelToken, attaches it to the request, and allows cancellation by calling cancelTokenSource.cancel(), handling cancellation errors appropriately.
If the request is canceled, you will see:
Request canceled Request cancelled by the user.
If the request is not canceled and an error occurs:
Error: Error: Request failed with status code 404
When you make an HTTP request using Axios and send a request to the server, you receive a response object. This object is populated with key properties containing information about the request and the response.
The core properties of the response object include:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const AxiosResponseExample = () => {
const [data, setData] = useState(null); // To store the fetched data
const [loading, setLoading] = useState(true); // To track loading state
const [error, setError] = useState(null); // To store any error that occurs
useEffect(() => {
// Axios GET request to fetch data from an API
axios.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
// On success, we store the response data
console.log('Response:', response); // Full Axios response object
setData(response.data); // Axios response contains 'data' property with actual data
setLoading(false); // Set loading to false after data is fetched
})
.catch((error) => {
// On error, we log the error and set the error state
console.error('Error response:', error.response); // Server's response in case of error
console.error('Error message:', error.message); // Error message
setError(error.message); // Store the error message
setLoading(false); // Stop loading even in case of error
});
}, []); // Empty dependency array ensures the effect runs only once on mount
// Render UI based on loading, error, or data state
if (loading) {
return <div>Loading...</div>; // Display loading indicator
}
if (error) {
return <div>Error: {error}</div>; // Display error message
}
return (
<div>
<h1>Fetched Posts</h1>
<ul>
{data.map(post => (
<li key={post.id}>{post.title}</li> // Render fetched post titles
))}
</ul>
</div>
);
};
export default AxiosResponseExample;
This React component uses Axios to fetch data from the jsonplaceholder API. It displays a loading message while fetching, shows an error message if an error occurs, and renders the list of post titles once the data is successfully fetched.
While loading: Loading...
On error: Error: [error message]
On success: A list of post titles, e.g.,
Fetched Posts
- Post Title 1
- Post Title 2
- Post Title 3
If there is a problem with the request, the promise returned by Axios will be rejected with an error object. This object contains the following properties:
A few of the compelling features that have made the Axios library so widely used in JavaScript applications for making HTTP requests are:
Here are the axios simplified methods such as:
axios.request(config): It is the base method for any HTTP call, where you can define configurations that suit your particular needs, such as URL, headers, data, etc.
axios.head(url[, config]): Sends a HEAD request to the specified URL. It's generally used to obtain some metadata without returning the response body. I would like to check out the headers.
axios.get(url[, config]): This method sends a GET request to the specified URL to retrieve data from the server. It is the most common HTTP method for retrieving information.
axios.post(url[, data[, config]]): Sends a POST request to the specified URL. It is used to send data to the server to create new resources or to submit form data.
axios.put(url[, data[, config]]): In general, PUT requests may be applied for most updates of resources already in place on a server. The new data is sent in the request's body.
axios.delete(url[, config]): Sends a DELETE request to the URL. Used generally for deleting the resources from the server, e.g., for deleting post accounts.
axios.options(url[, config]): OPTIONS requests server communications to check what HTTP methods and other options are supported. Useful for checking CORS settings.
axios.patch(url[, data[, config]]): Sends a PATCH request to the server to partially update a resource. It's similar but only replaces parts of a resource, modifying specific fields.
In conclusion, installing axios in react.js can efficiently enhance the performance of your application and facilitate API integration. From fundamental to advanced features like interceptors and request cancellation, axios provides flexibility and efficient data management. Axios with react gives your web application powerful API interaction capabilities.
Axios is a React-based HTTP client that can easily connect a React application to APIs or other backend services. It makes retrieving or submitting data easy when sending requests like GET, POST, PUT, and DELETE.
Axios is used as it provides a simple interface for performing the HTTP requests; it automatically converts JSON data for our response, has request and response interceptors, can cancel requests, and handles errors in a better way, and that's what makes this a popular option to perform API calls in React.
A Javascript library in npm allows developers to make HTTP requests using Axios. A promise-based HTTP client for the browser and node.js, it makes working with APIs easier.
No, Axios is not a REST API. Instead, it is an HTTP client library that can interact with any REST API by making HTTP requests, such as GET, POST, PUT, or DELETE.
React.js Roadmap for 2025: Beginner to Advanced - Follow the best React.js roadmap to master essential skills, from beginner basics to advanced concepts, and become a skilled React developer. (02 Jan 2026, 6 min read)
What are the Features of React.js? - Learn the key features of React.js, including its component-based structure, virtual DOM, and efficient rendering, making it ideal for building interactive UIs. (02 Jan 2026, 5 min read)
Contact Information:
About NxtWave:
NxtWave is an educational technology organization providing comprehensive training programs in software development, data analysis, and AI technologies. They offer various courses including NxtWave Academy and NxtWave Intensive programs designed to help students and professionals build careers in technology.