React Axios Delete Request Example

In React, Axios is a popular library used to handle HTTP requests. While GET and POST requests are often used, DELETE requests are equally important when it comes to removing data from a server or database.

Why Use Axios for DELETE Requests in React?

Axios simplifies HTTP requests by providing a clean API and built-in methods for handling responses and errors. With Axios, DELETE requests are straightforward and require minimal setup. Here are a few reasons to use Axios for DELETE requests in React:

  1. Simplicity: Axios has a clean, promise-based syntax that works well with React’s asynchronous functions.
  2. Error Handling: Axios makes it easy to handle errors and display feedback to the user.
  3. Interceptors: You can use Axios interceptors to apply specific configurations to each request, making it easy to handle headers, authentication, and error responses globally.

How DELETE Requests Work in Axios

DELETE requests in Axios follow a simple syntax. When you want to delete a specific item on the server, you generally send the DELETE request with the item’s unique identifier (often the id) as part of the URL.

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 to the specified URL.
  • then(): This handles the response if the request is successful.
  • catch(): This handles errors if the request fails.

Example: Implementing a DELETE Request in a React Application

Imagine you’re building a React application that displays a list of products, and each product has a delete button. When clicked, the product is deleted from both the server and the displayed list. Here’s how you can implement this functionality using Axios.

Step 1: Setting Up the Component and State

First, create a ProductList component that fetches and displays a list of products. We’ll use state to hold the list of products and update it after each deletion.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function ProductList() {
const [products, setProducts] = useState([]);

useEffect(() => {
// Fetch products when the component mounts
axios.get('https://api.example.com/products')
.then(response => {
setProducts(response.data);
})
.catch(error => {
console.error('Error fetching products:', error);
});
}, []);

return (
<div>
<h2>Product List</h2>
<ul>
{products.map((product) => (
<li key={product.id}>
{product.name} - ${product.price}
<button onClick={() => handleDelete(product.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}

In this code:

  • products: Holds the list of products fetched from the server.
  • useEffect: Fetches the list of products when the component mounts.

Step 2: Defining the handleDelete Function

Next, define the handleDelete function, which sends a DELETE request to the server and updates the products array in state if the deletion is successful.

const handleDelete = (id) => {
axios.delete(`https://api.example.com/products/${id}`)
.then(response => {
console.log('Product deleted:', response.data);

// Update the products list to remove the deleted item
setProducts(products.filter(product => product.id !== id));
})
.catch(error => {
console.error('Error deleting product:', error);
});
};

Explanation:

  • handleDelete(id): This function takes the id of the product to delete.
  • axios.delete: Sends a DELETE request to the endpoint with the product’s id.
  • setProducts: Updates the state by filtering out the deleted product from the list.
  • catch: Logs any error to the console if the request fails.

Step 3: Integrating handleDelete with the Component

In the component’s JSX, call handleDelete when the “Delete” button is clicked.

return (
<div>
<h2>Product List</h2>
<ul>
{products.map((product) => (
<li key={product.id}>
{product.name} - ${product.price}
<button onClick={() => handleDelete(product.id)}>Delete</button>
</li>
))}
</ul>
</div>
);

Full Code Example

Putting it all together, here’s the complete code:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function ProductList() {
const [products, setProducts] = useState([]);

// Fetch products from the server
useEffect(() => {
axios.get('https://api.example.com/products')
.then(response => {
setProducts(response.data);
})
.catch(error => {
console.error('Error fetching products:', error);
});
}, []);

// Delete a product by ID
const handleDelete = (id) => {
axios.delete(`https://api.example.com/products/${id}`)
.then(response => {
console.log('Product deleted:', response.data);

// Update state to remove deleted product
setProducts(products.filter(product => product.id !== id));
})
.catch(error => {
console.error('Error deleting product:', error);
});
};

return (
<div>
<h2>Product List</h2>
<ul>
{products.map((product) => (
<li key={product.id}>
{product.name} - ${product.price}
<button onClick={() => handleDelete(product.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}

export default ProductList;

Handling DELETE Request Errors Gracefully

It’s essential to handle errors so the user can understand if the deletion fails. You might want to add an error message or notification to improve user experience.

const handleDelete = (id) => {
axios.delete(`https://api.example.com/products/${id}`)
.then(response => {
console.log('Product deleted:', response.data);
setProducts(products.filter(product => product.id !== id));
})
.catch(error => {
alert('Could not delete the product. Please try again.');
console.error('Error deleting product:', error);
});
};

Leave a Comment