Using Axios in React
1. Introduction to Axios
Axios is a JavaScript library used to make HTTP requests from React applications to external APIs and backend servers. It supports GET, POST, PUT, PATCH and DELETE requests.
Axios automatically converts JSON response data into JavaScript objects. It also provides convenient error handling and request configuration options.
2. Installing Axios
Open your React project's terminal and execute the following command:
npm install axios
After installation, import Axios into your component:
import axios from "axios";
3. Fetching Data Using Axios GET
The axios.get() method sends a GET request to retrieve
information from an API. The response data is available through
response.data.
import axios from "axios";
async function getUsers() {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
console.log(response.data);
} catch (error) {
console.error("Error fetching users:", error.message);
}
}
getUsers();
4. Displaying API Data in React
We can combine Axios with React's useState and
useEffect hooks to fetch and display data when a
component loads.
import { useEffect, useState } from "react";
import axios from "axios";
function AxiosUsers() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
async function fetchUsers() {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
setUsers(response.data);
} catch (err) {
setError("Unable to load users. Please try again.");
} finally {
setLoading(false);
}
}
fetchUsers();
}, []);
if (loading) {
return <p>Loading users...</p>;
}
if (error) {
return <p role="alert">{error}</p>;
}
return (
<div>
<h2>User List</h2>
{users.length === 0 ? (
<p>No users found.</p>
) : (
<ul>
{users.map((user) => (
<li key={user.id}>
<strong>{user.name}</strong>
{" - "}
{user.email}
</li>
))}
</ul>
)}
</div>
);
}
export default AxiosUsers;
5. Sending POST Requests Using Axios
The axios.post() method sends data to a server.
The first argument is the API URL, and the second argument
contains the data to send.
import axios from "axios";
async function createUser() {
const newUser = {
name: "Samadhan",
email: "samadhan@example.com"
};
try {
const response = await axios.post(
"https://jsonplaceholder.typicode.com/users",
newUser
);
console.log("Created user:", response.data);
} catch (error) {
console.error("Error creating user:", error.message);
}
}
createUser();
6. Axios Error Handling
Axios errors can be handled in a catch block. We can check whether the server returned an error response, the request received no response, or the request could not be configured or sent.
import axios from "axios";
async function fetchData() {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
console.log(response.data);
} catch (error) {
if (axios.isAxiosError(error)) {
if (error.response) {
console.error(
"Server error:",
error.response.status
);
} else if (error.request) {
console.error(
"No response received from the server."
);
} else {
console.error(
"Request error:",
error.message
);
}
} else {
console.error("Unexpected error:", error);
}
}
}
fetchData();
7. Fetch API vs Axios
| Feature | Fetch API | Axios |
|---|---|---|
| Installation | Built into modern browsers | Requires installation |
| JSON Response | Call response.json() |
Available in response.data |
| HTTP Errors | Check response.ok |
Rejects non-success status codes by default |
| POST Requests | Configure method, headers and body | Use axios.post(url, data) |
| Request Interceptors | Not built in | Supported |
8. Axios Request Flow
9. Best Practices
- Keep API request logic organized in reusable functions.
- Use loading and error states to improve the user experience.
- Use environment variables for configurable API base URLs.
- Do not expose secret API keys in frontend environment variables.
- Use Axios interceptors when shared request or response handling is needed.
- Cancel or ignore outdated requests when necessary, especially when components unmount or parameters change.
10. Practice Tasks
- Install Axios in your React project.
- Fetch users using
axios.get(). - Display user names and email addresses.
- Send a POST request with a new user's details.
- Display loading and error messages.
- Compare the same GET request using Fetch and Axios.
Summary
Axios simplifies API integration in React by providing convenient methods for HTTP requests, automatic JSON response transformation and promise-based error handling. By combining Axios with React hooks, loading states and error handling, we can build reliable applications that communicate effectively with backend APIs.