How to Use Axios in React: A Step-by-Step Guide
In this article, you will learn how to integrate and use the Axios
library in a React application to fetch and manage API data. We will
cover the installation process, making basic GET and POST requests,
handling errors, and utilizing React hooks like useEffect
and useState to display the retrieved data in your
components.
Installing Axios
To get started, you need to install the Axios package in your existing React project. Open your terminal, navigate to your project directory, and run one of the following commands:
Using npm:
npm install axiosUsing yarn:
yarn add axiosMaking a GET Request
The most common use case for Axios is fetching data from an external
API. To do this inside a React component, you typically combine Axios
with the useState hook to store the data and the
useEffect hook to trigger the request when the component
mounts.
Here is a complete example of fetching a list of users:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then((response) => {
setUsers(response.data);
setLoading(false);
})
.catch((err) => {
setError(err.message);
setLoading(false);
});
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default UserList;Making a POST Request
To send data to a server, such as submitting a form, you use the
axios.post method. This method takes the destination URL as
the first argument and the data object you want to send as the second
argument.
Here is how to implement a POST request inside a React component:
import React, { useState } from 'react';
import axios from 'axios';
function CreateUser() {
const [name, setName] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
axios.post('https://jsonplaceholder.typicode.com/users', { name })
.then((response) => {
console.log('User created:', response.data);
alert(`User ${response.data.name} created successfully!`);
})
.catch((error) => {
console.error('There was an error creating the user!', error);
});
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter name"
/>
<button type="submit">Add User</button>
</form>
);
}
export default CreateUser;Using Async/Await Syntax
For cleaner and more readable asynchronous code, you can use
async/await inside your useEffect hook.
Because the effect callback itself cannot be asynchronous, you must
define the async function inside the hook and call it immediately.
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
setUsers(response.data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchData();
}, []);