Axios in React.js
Axios in React.js
What is Axios?
Axios is
a popular JavaScript library used to make HTTP requests (GET, POST, PUT,
DELETE) in React applications. It is based on Promises and provides a
simple way to interact with APIs.
Why Use Axios?
✅ Supports request and response interceptors
✅ Handles automatic JSON conversion
✅ Supports error handling
✅ Can cancel requests using abort controllers
✅ Works in browsers and Node.js
1. Installing Axios in React
Before
using Axios, install it in your React project:
npm install axios
2. Making a GET Request (Fetching Data)
Axios is
commonly used to fetch data from an API inside useEffect().
Example: Fetching Data with Axios (GET Request)
Key Points
- axios.get(URL) fetches data.
- response.data contains the API response.
- useEffect(() => {}, []) ensures the API call
happens only once on mount.
3. Making a POST Request (Sending Data)
Axios can
also send data to a server.
Example: Sending Data with Axios (POST Request)
import React, { useState } from "react";
import axios from "axios";
const AddUser = () => {
const
[name, setName] = useState("");
const
[email, setEmail] = useState("");
const
handleSubmit = async (e) => {
e.preventDefault();
const
newUser = { name, email };
try {
const
response = await axios.post("https://jsonplaceholder.typicode.com/users",
newUser);
console.log("User added:", response.data);
} catch
(error) {
console.error("Error adding user:", error);
}
};
return (
<div>
<h2>Add User</h2>
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Name"
onChange={(e) => setName(e.target.value)} />
<input type="email" placeholder="Email"
onChange={(e) => setEmail(e.target.value)} />
<button type="submit">Submit</button>
</form>
</div>
);
};
export default AddUser;
Key Points
- axios.post(URL, data) sends data to the API.
- await axios.post(...) ensures asynchronous
handling.
- try-catch handles API request errors.
4. Making a PUT Request (Updating Data)
Use PUT to update an existing resource.
Example: Updating User Data (PUT Request)
import axios from "axios";
const updateUser = async (id) => {
try {
const
response = await axios.put(`https://jsonplaceholder.typicode.com/users/${id}`,
{
name:
"Updated Name",
email:
"updated@example.com"
});
console.log("User updated:", response.data);
} catch
(error) {
console.error("Error updating user:", error);
}
};
Key Points
- axios.put(URL, data) updates an existing
resource.
- Requires an ID to
specify which record to update.
5. Making a DELETE Request (Deleting Data)
Use DELETE to remove a resource.
Example: Deleting a User (DELETE Request)
import axios from "axios";
const deleteUser = async (id) => {
try {
await
axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`);
console.log("User deleted successfully");
} catch
(error) {
console.error("Error deleting user:", error);
}
};
Key Points
- axios.delete(URL) removes a record.
- Pass the ID of the
record to delete.
6. Handling Errors with Axios
To handle
errors properly, use try-catch blocks or catch().
axios.get("https://jsonplaceholder.typicode.com/users")
.then(response => console.log(response.data))
.catch(error => {
if (error.response)
{
console.error("Server responded with error:",
error.response.data);
} else if
(error.request) {
console.error("No response received:", error.request);
} else {
console.error("Request error:", error.message);
}
});
7. Using Axios with async-await (Best Practice)
Instead
of .then(), using async-await makes the code cleaner.
const fetchUsers = async () => {
try {
const
response = await
axios.get("https://jsonplaceholder.typicode.com/users");
console.log(response.data);
} catch
(error) {
console.error("Error fetching users:", error);
}
};
8. Axios Interceptors (Global Request &
Response Handlers)
Interceptors
allow modifying requests before they are sent and handling responses globally.
Example: Adding a Token to Every Request
import axios from "axios";
axios.interceptors.request.use(
(config)
=> {
config.headers.Authorization = "Bearer YOUR_ACCESS_TOKEN";
return
config;
},
(error)
=> Promise.reject(error)
);
Key Points
- Useful for adding
authentication tokens.
- Can log responses
globally before they reach components.
Comparison: Axios vs Fetch API
|
Feature |
Axios |
Fetch API |
|
Automatic
JSON Handling |
✅ Yes |
❌ No (needs .json()) |
|
Request
& Response Interceptors |
✅ Yes |
❌ No |
|
Supports
async-await |
✅ Yes |
✅ Yes |
|
Error
Handling |
✅ Better (with error.response) |
❌ Manual handling needed |
|
Cancel
Requests |
✅ Yes (AbortController) |
✅ Yes (AbortController) |
Conclusion
- Axios simplifies API calls
in React.
- Use GET for fetching data, POST for sending, PUT for updating, and DELETE for removal.
- Best Practices:
- Use async-await for better readability.
- Use interceptors for
authentication.
- Always handle errors
properly.
Thank you for sharing this informative article. It covers important aspects of academic writing that many students often overlook. Finding trustworthy academic guidance can be challenging, so anyone searching for legit essay help should always choose experienced professionals who value originality and academic standards. I especially liked the practical tips on organizing ideas and presenting clear arguments. This blog is an excellent resource for students aiming to improve their writing confidence and overall academic performance. Looking forward to reading more insightful posts from your website.
ReplyDelete