Axios is a JavaScript library used to make HTTP requests. In React applications, Axios can be used to communicate with APIs and retrieve, create, update, or delete data from a server.
useEffect and useState
when working with API data.
Axios is a Promise-based HTTP client for JavaScript applications.
It can be used to communicate with APIs and web servers.
React
↓
Axios
↓
API
↓
Server
Axios makes HTTP requests convenient and provides features that are useful when working with APIs.
It can be used for:
Axios can be installed using npm.
npm install axios
After installation, Axios can be imported into React components.
Import Axios into your React component using:
import axios from "axios";
You can then use the Axios methods to make HTTP requests.
The axios.get() method is used to retrieve data.
axios.get("/api/students")
.then(response => {
console.log(response.data);
});
The response data is available through response.data.
An Axios response contains useful information about the HTTP request.
axios.get("/api/students")
.then(response => {
console.log(response.data);
console.log(response.status);
});
The data property contains the response body.
In React, Axios is commonly used inside useEffect when data
should be requested after rendering.
import {
useEffect
} from "react";
import axios from "axios";
function Students() {
useEffect(() => {
axios.get("/api/students")
.then(response => {
console.log(response.data);
});
}, []);
return <h2>Students</h2>;
}
import {
useEffect,
useState
} from "react";
import axios from "axios";
function Students() {
const [students, setStudents] = useState([]);
useEffect(() => {
axios.get("/api/students")
.then(response => {
setStudents(response.data);
});
}, []);
return <h2>Students</h2>;
}
After storing the response data in state, you can display it in JSX.
{students.map(student => (
<p key={student.id}>
{student.name}
</p>
))}
This example assumes the API returns an array of student objects.
Axios works well with the async/await syntax.
async function getStudents() {
const response = await axios.get(
"/api/students"
);
console.log(response.data);
}
An asynchronous function can be created inside the effect and then called.
useEffect(() => {
async function loadStudents() {
const response = await axios.get(
"/api/students"
);
setStudents(response.data);
}
loadStudents();
}, []);
The axios.post() method is used to send data to a server.
axios.post("/api/students", {
name: "Rahul",
course: "React"
})
.then(response => {
console.log(response.data);
});
Form values can be sent to an API using Axios.
const student = {
name: "Amit",
email: "amit@example.com",
course: "React"
};
axios.post(
"/api/students",
student
)
.then(response => {
console.log(response.data);
});
The axios.put() method can be used to update a resource.
axios.put("/api/students/101", {
name: "Rahul Kumar",
course: "React"
})
.then(response => {
console.log(response.data);
});
The axios.patch() method can be used when you want to update
specific parts of a resource.
axios.patch("/api/students/101", {
course: "Advanced React"
})
.then(response => {
console.log(response.data);
});
The axios.delete() method is used to request deletion of a
resource.
axios.delete("/api/students/101")
.then(response => {
console.log(response.data);
});
Axios requests can be handled with catch().
axios.get("/api/students")
.then(response => {
setStudents(response.data);
})
.catch(error => {
console.log(error);
});
const [error, setError] = useState("");
useEffect(() => {
axios.get("/api/students")
.then(response => {
setStudents(response.data);
})
.catch(error => {
setError(error.message);
});
}, []);
The error message can then be displayed in the UI.
const [loading, setLoading] = useState(true);
useEffect(() => {
axios.get("/api/students")
.then(response => {
setStudents(response.data);
})
.finally(() => {
setLoading(false);
});
}, []);
The finally() block can run after the request completes,
regardless of whether it succeeds or fails.
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
This provides feedback to users while API data is being loaded or when a request fails.
Axios can work with route parameters to retrieve a specific resource.
const { id } = useParams();
useEffect(() => {
axios.get(`/api/students/${id}`)
.then(response => {
setStudent(response.data);
});
}, [id]);
Axios requests can receive configuration options.
axios.get("/api/students", {
headers: {
Authorization: "Bearer TOKEN"
}
})
.then(response => {
console.log(response.data);
});
Configuration can include headers, parameters, timeout settings, and other request options.
Axios can send query parameters using the params option.
axios.get("/api/students", {
params: {
course: "React",
page: 1
}
})
.then(response => {
console.log(response.data);
});
This can result in a request containing query parameters such as
?course=React&page=1.
For larger applications, an Axios instance can be created with common configuration.
import axios from "axios";
const api = axios.create({
baseURL: "/api"
});
export default api;
The instance can then be reused for API requests.
import api from "./api";
api.get("/students")
.then(response => {
console.log(response.data);
});
The baseURL configured in the instance is automatically used.
Axios supports interceptors that can process requests or responses before they are handled by application code.
api.interceptors.request.use(
config => {
return config;
}
);
Interceptors can be useful for common request or response handling.
Axios can be used to submit React form data to a backend API.
async function handleSubmit(e) {
e.preventDefault();
await axios.post(
"/api/students",
formData
);
}
This pattern is commonly used for registration, admission, contact, and other forms.
A common React Axios workflow is:
React Component
↓
Axios Request
↓
API
↓
Server
↓
Axios Response
↓
setState()
↓
Updated UI
import {
useEffect,
useState
} from "react";
import axios from "axios";
function Students() {
const [students, setStudents] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
async function loadStudents() {
try {
const response = await axios.get(
"/api/students"
);
setStudents(response.data);
} catch (err) {
setError(
err.message
);
} finally {
setLoading(false);
}
}
loadStudents();
}, []);
if (loading) {
return (
<h3>
Loading students...
</h3>
);
}
if (error) {
return (
<h3>
Error: {error}
</h3>
);
}
return (
<div>
<h2>
Student List
</h2>
{students.map(student => (
<div
key={student.id}
className="card mt-3"
>
<div className="card-body">
<h4>
{student.name}
</h4>
<p>
Course: {student.course}
</p>
</div>
</div>
))}
</div>
);
}
export default Students;
useEffect for appropriate data-fetching effects.useState for data that affects the UI.async/await when it improves readability.Axios
↓
Request
↓
API
↓
Response
↓
State
↓
UI
npm install axios.axios.get() to retrieve data.axios.post() to send data.axios.put() or axios.patch() to update data.axios.delete() to delete a resource.response.data.useEffect and useState.Question: Which command is used to install Axios in a React project?