How to fetch data in React with Axios
Fetching data in React with Axios provides enhanced HTTP client features including request interceptors, automatic JSON parsing, and better error handling. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented Axios in countless React applications for complex API integrations and enterprise data management. From my expertise, the most effective approach is using Axios with useEffect hook for robust HTTP requests with built-in features. This method provides superior error handling, request configuration, and response transformation compared to native fetch.
Use axios
with useEffect
hook for enhanced HTTP requests with automatic JSON parsing.
import { useState, useEffect } from 'react'
import axios from 'axios'
function ProductList() {
const [products, setProducts] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
const fetchProducts = async () => {
try {
setLoading(true)
const response = await axios.get('/api/products', {
timeout: 5000,
headers: {
'Authorization': 'Bearer token123'
}
})
setProducts(response.data)
} catch (err) {
setError(err.response?.data?.message || err.message)
} finally {
setLoading(false)
}
}
fetchProducts()
}, [])
if (loading) return <div>Loading products...</div>
if (error) return <div>Error: {error}</div>
return (
<div>
<h2>Products</h2>
{products.map(product => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>${product.price}</p>
</div>
))}
</div>
)
}
Axios automatically parses JSON responses and provides better error handling with response status codes. Use configuration objects for headers, timeouts, and request options. Access detailed error information through err.response for comprehensive error handling and user feedback.
Best Practice Note:
This is the same Axios approach we use in CoreUI React components for enterprise-grade API communication.
Install with npm install axios
and consider creating Axios instances with base configurations for consistent API communication across your application.