Axios is a popular JavaScript library that simplifies making HTTP requests, especially in client-side applications like React. It is promise-based and provides an easy-to-use API for performing network requests (GET, POST, PUT, DELETE, etc.). Axios is an alternative to the native Fetch API but provides additional features such as interceptors, automatic JSON data transformation, and better error handling.
In React, you can use Axios to fetch data from APIs or submit forms to a backend. Here’s how you can use Axios in your React application.
Setting Up Axios in React
- Install Axios First, you need to install the Axios library using npm or yarn.
npm install axios
- Import Axios in your Component Once Axios is installed, you can import it in your React components where you need to perform API requests.
import axios from 'axios';
Basic GET Request with Axios
To make a simple GET request with Axios, you can use the .get()
method. This method returns a promise that resolves to the response of the request.
Here’s how to use Axios to fetch data in a React component:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const FetchDataWithAxios = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
axios
.get('https://api.example.com/data')
.then((response) => {
setData(response.data); // Set fetched data to state
setLoading(false); // Set loading to false after data is fetched
})
.catch((err) => {
setError(err.message); // Handle error in case of failure
setLoading(false); // Set loading to false in case of error
});
}, []); // The empty array means this will run once when the component mounts
if (loading) {
return <p>Loading...</p>; // Show loading message
}
if (error) {
return <p>Error: {error}</p>; // Show error message
}
return (
<div>
<h1>Fetched Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default FetchDataWithAxios;
Making POST Requests with Axios
To send data to a server, you can use Axios’s .post()
method. You typically use this to submit forms or create new resources on the backend.
Here’s an example of how to make a POST request using Axios:
import React, { useState } from 'react';
import axios from 'axios';
const PostDataWithAxios = () => {
const [formData, setFormData] = useState({
name: '',
email: ''
});
const [responseMessage, setResponseMessage] = useState('');
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prevData) => ({
...prevData,
[name]: value
}));
};
const handleSubmit = (e) => {
e.preventDefault();
axios
.post('https://api.example.com/submit', formData)
.then((response) => {
setResponseMessage('Form submitted successfully!');
console.log(response.data);
})
.catch((error) => {
setResponseMessage('Error submitting the form');
console.error(error);
});
};
return (
<div>
<h1>Submit Form</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Your Name"
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Your Email"
/>
<button type="submit">Submit</button>
</form>
<p>{responseMessage}</p>
</div>
);
};
export default PostDataWithAxios;
Using Axios with Async/Await
While using .then()
and .catch()
works well with Axios, using async/await provides a cleaner, more readable approach for handling asynchronous code.
Here’s how you can use async/await with Axios in a React component:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const FetchDataWithAxiosAsync = () => {
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://api.example.com/data');
setData(response.data);
setLoading(false);
} catch (err) {
setError(err.message);
setLoading(false);
}
};
fetchData();
}, []);
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
return (
<div>
<h1>Fetched Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default FetchDataWithAxiosAsync;
Axios Interceptors
Axios provides the ability to set up interceptors that allow you to run custom code before a request is sent or after a response is received. Interceptors are useful for tasks like adding authorization headers or handling errors globally.
Here’s an example of setting up an interceptor to add an authorization token:
import axios from 'axios';
// Add a request interceptor to add the token to all requests
axios.interceptors.request.use(
(config) => {
const token = localStorage.getItem('auth_token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Add a response interceptor to handle global errors
axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
console.error('API Error:', error);
return Promise.reject(error);
}
);
Canceling Requests with Axios
In some cases, you may want to cancel an API request, such as when the user navigates away from the page before the request is completed. Axios supports cancel tokens that allow you to cancel an ongoing request.
Here’s how to cancel a request with Axios:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const CancelRequestWithAxios = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const source = axios.CancelToken.source();
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data', {
cancelToken: source.token,
});
setData(response.data);
setLoading(false);
} catch (err) {
if (axios.isCancel(err)) {
console.log('Request canceled', err.message);
} else {
setError(err.message);
}
setLoading(false);
}
};
fetchData();
// Clean up the request on component unmount
return () => {
source.cancel('Request canceled by user');
};
}, []);
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
return (
<div>
<h1>Fetched Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default CancelRequestWithAxios;