Axios is a popular library for making HTTP requests in JavaScript, and it’s often used in React applications because of its simplicity and powerful features. It works with promises and supports features like request cancellation, interceptors, and handling JSON data automatically.
Why Use Axios?
- Automatic JSON Parsing: Axios parses JSON responses by default.
- Simplified Syntax: Cleaner syntax compared to the Fetch API.
- Request and Response Interceptors: Modify requests or handle errors globally.
- Error Handling: Provides better error handling (e.g., differentiates between HTTP errors and network errors).
- Browser Compatibility: Supports older browsers better than
fetch()
.
Installing Axios
To use Axios in your React app, first install it using npm or yarn:
npm install axios
Basic Axios Syntax
axios.get(url, config); // For GET requests axios.post(url, data, config); // For POST requests
Using Axios in React
1. Fetching Data (GET Request)
import React, { useState, useEffect } from 'react'; import axios from 'axios'; const App = () => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await axios.get('https://jsonplaceholder.typicode.com/posts'); setData(response.data); // Axios automatically parses JSON setLoading(false); } catch (error) { setError(error.message); setLoading(false); } }; fetchData(); }, []); if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error}</p>; return ( <div> <h1>Posts</h1> <ul> {data.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> </div> ); }; export default App;
2. Sending Data (POST Request)
import React, { useState } from 'react'; import axios from 'axios'; const App = () => { 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:', error); } }; return ( <div> <h1>Create Post</h1> <form onSubmit={handleSubmit}> <input type="text" placeholder="Title" value={title} onChange={(e) => setTitle(e.target.value)} /> <textarea placeholder="Body" value={body} onChange={(e) => setBody(e.target.value)} ></textarea> <button type="submit">Submit</button> </form> {response && ( <div> <h2>Response</h2> <p>Post created with ID: {response.id}</p> </div> )} </div> ); }; export default App;
3. Using Axios with Interceptors
Interceptors allow you to modify requests or responses globally.
import axios from 'axios'; // Add a request interceptor axios.interceptors.request.use( (config) => { config.headers.Authorization = 'Bearer YOUR_ACCESS_TOKEN'; return config; }, (error) => Promise.reject(error) ); // Add a response interceptor axios.interceptors.response.use( (response) => response, (error) => { console.error('Error occurred:', error.response); return Promise.reject(error); } );
4. Canceling Requests
Axios allows you to cancel requests using AbortController
.
import React, { useState, useEffect } from 'react'; import axios from 'axios'; const App = () => { const [data, setData] = useState(null); useEffect(() => { const controller = new AbortController(); // Create AbortController const fetchData = async () => { try { const response = await axios.get('https://jsonplaceholder.typicode.com/posts', { signal: controller.signal, // Attach signal to the request }); setData(response.data); } catch (error) { if (axios.isCancel(error)) { console.log('Request canceled'); } else { console.error('Error:', error); } } }; fetchData(); return () => { controller.abort(); // Cancel request on cleanup }; }, []); return ( <div> <h1>Posts</h1> {data && data.map((post) => <p key={post.id}>{post.title}</p>)} </div> ); }; export default App;
Best Practices with Axios
- Global Axios Instance: Create a pre-configured Axios instance for reusable configurations.
import axios from 'axios'; const axiosInstance = axios.create({ baseURL: 'https://jsonplaceholder.typicode.com', headers: { 'Content-Type': 'application/json' }, }); export default axiosInstance;
Usage:
import axiosInstance from './axiosInstance'; axiosInstance.get('/posts');
- Error Handling: Handle API errors centrally.
axios.interceptors.response.use( (response) => response, (error) => { console.error('API Error:', error.response || error.message); return Promise.reject(error); } );
- Pagination: For large datasets, implement pagination to fetch data in chunks.
axios.get('/posts', { params: { _page: 1, _limit: 10 } });
Axios vs Fetch
Feature | Axios | Fetch |
---|---|---|
JSON Parsing | Automatic | Requires .json() |
Error Handling | Better (throws for non-2xx responses) | Limited |
Request Interceptors | Built-in | Needs manual setup |
Cancellation | Built-in with AbortController |
Native support now |
Browser Support | Supports older browsers | Modern browsers |