What Is Axios In React?
Axios is a tool (popular library) of react. that help you to talk with server. you can use Axios to Get data (GET request) from the server, send data (POST request) to the server and also delete data from the server (DELETE request).
GET and POST are commonly used but DELETE is also very important when you want to remove something like a user, item or post from the database or server.
Why Use Axios for DELETE Requests in React?
Axios makes simple and clean in react to deleting data from a server. Below we describe why it is easy to use:
- Simplicity: Axios use a simple and clear code to require minimul setup. it is work with async and await function, so you can write clean and easy to read code when deleting something from server.
- Error Handling: If something goes wrong during the request like no internet, server error or wrong ID, so Axios easily catch that error and show a message to user like “Item could not be deleted”.
- Middleware (Optional Feature): Axios allow you to set rules for every request in one place. For example: (1) Automatically add your API key to every request. (2) Handle “unauthorized” errors globally (This helps if your app needs any authentication).
How DELETE Requests Work in Axios
You send a DELETE request when you want to delete something from the server, you usually use the item’s unique ID in the URL like user ID, post ID to tell the server what you want to delete.
For example:
axios.delete(`https://api.example.com/users/5`)
This means:
“Please delete the user with ID 5 from the server.”
Axios sends this request to the database and if the item exists, so the server will remove ID 5.
Basic Syntax for a DELETE Request in Axios
axios.delete('https://api.example.com/items/1')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
In this syntax:
- axios.delete(url): This method sends a DELETE request.
- then(): handles the response if the request is successful.
- catch(): handles errors if the request fails.
Example: Implementing a DELETE Request in a React Application
Imagine you are building a new React application that displays a list of products and each product has a delete button. when you click on the delete button, the product is deleted from both the server and the display list. Here we explained how you can do this with Axios:
Step 1: Set the Component and State
First, we create ProductList component that fetch and display product list. we are use state to hold the list of products and update it after delete each product.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function FruitInventory() {
const [fruitData, setFruitData] = useState([]);
useEffect(() => {
// Fetch fruit items from server when component loads
axios.get('https://api.example.com/fruits')
.then((response) => {
setFruitData(response.data);
})
.catch((err) => {
console.error('Unable to fetch fruit data:', err);
});
}, []);
Simple Explanation:
- FruitInventory: This is the main component to display fruits.
- fruitData: This state hold the list of fruit items those we get from the server.
- useEffect: It run only one time after the component is shown on the screen and fetch the fruits.
- axios.get(. . .): Send the GET request for get the fruit list.
- .then(. . .): On success, we save that list in fruitData.
- .catch(. . .): If the server fails to respond, so show an error.
Step 2: Handling the Delete Function
Now we add a function that delete a fruit from the server.
const removeFruit = (fruitId) => {
axios.delete(`https://api.example.com/fruits/${fruitId}`)
.then((res) => {
console.log('Deleted fruit:', res.data);
// Update local state after deletion
setFruitData(fruitData.filter(item => item.id !== fruitId));
})
.catch((error) => {
console.error('Delete failed:', error);
});
};
Simple Explanation:
- removeFruit: When you click the “Delete” button so this function run..
- It sends a DELETE request to the server for the selected fruit item.
- After a successful deletion, we update our fruitData state and remove that item from the list.
- We use filter() to keep those items that don’t match the deleted ID.
- If something goes wrong so we log the error.
Step 3: Displaying Items & Delete Button in UI
This part of code will show all fruit items with a “Delete” button.
return (
<div>
<h2>Fruit Basket</h2>
<ul>
{fruitData.map((fruit) => (
<li key={fruit.id}>
{fruit.name} - ₹{fruit.price}
<button onClick={() => removeFruit(fruit.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default FruitInventory;
Simple Explanation:
- We show each fruit using .map() function.
- We display its name and price for every item, .
- A “Delete” button is placed with each item.
- When click on the button, it calls removeFruit with that fruit’s ID to delete the fruit.