Using Axios to Handle API Requests in React
In modern web applications, fetching data from APIs is an essential task. While you can use JavaScript’s built-in fetch, many React developers prefer Axios, a popular promise-based HTTP client, because of its simplicity, ease of use, and advanced features like request/response interceptors.
🚀 Why Use Axios in React?
Axios offers several benefits over the native fetch API:
✅ Cleaner syntax for GET, POST, PUT, DELETE, etc.
✅ Automatic JSON data transformation
✅ Built-in support for request cancellation
✅ Interceptors to handle authentication tokens or global error handling
✅ Better error reporting than fetch
🛠️ Installing Axios
First, install Axios in your React project using npm or yarn:
npm install axios
# or
yarn add axios
📥 Making a GET Request
You can use Axios inside React components to fetch data when a component mounts. Here’s an example using useEffect to fetch a list of users from an API:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function UserList() {
const [users, setUsers] = useState([]);
const [error, setError] = useState('');
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => setUsers(response.data))
.catch(error => setError('Error fetching users'));
}, []);
return (
<div>
<h2>Users</h2>
{error && <p style={{ color: 'red' }}>{error}</p>}
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
</div>
);
}
export default UserList;
📤 Making a POST Request
Axios makes it easy to send data with POST requests. Here’s an example of submitting a new post:
function createPost() {
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'My New Post',
body: 'This is the post content.',
userId: 1
})
.then(response => console.log('Post created:', response.data))
.catch(error => console.error('Error creating post:', error));
}
🔄 Setting Global Configurations
You can configure a default base URL and headers to avoid repeating them in every request:
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN';
🛡️ Using Interceptors for Authentication
Axios interceptors are powerful for adding tokens or handling global errors:
axios.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
}, error => Promise.reject(error));
✅ Conclusion
Axios simplifies making API calls in React with a cleaner syntax and powerful features like interceptors and global configurations. By mastering Axios, you can handle complex API interactions more efficiently, improve code readability, and build more maintainable React applications.
Learn MERN Stack Training Course
Read More:
CRUD Operations Using MERN Stack
Building a To-Do App Using MERN Stack
Authentication in MERN Stack Using JWT
React Router DOM: Simplifying Navigation
Visit Quality Thought Training Institute
Comments
Post a Comment