0% found this document useful (0 votes)
9 views

DeleteProduct JSX

delete product react code
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

DeleteProduct JSX

delete product react code
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import React, { useState, useEffect } from "react";

import "./DeleteProduct.css";

const DeleteProduct = () => {


const [products, setProducts] = useState([]);
const [selectedProduct, setSelectedProduct] = useState("");

// Fetch products from backend


useEffect(() => {
fetch("http://localhost:4000/products")
.then((resp) => resp.json())
.then((data) => setProducts(data.products));
}, []);

// Delete selected product


const deleteProduct = async () => {
if (!selectedProduct) {
alert("Please select a product to delete.");
return;
}

await fetch(`http://localhost:4000/deleteproduct/${selectedProduct}`, {
method: "DELETE",
headers: {
Accept: "application/json",
},
})
.then((resp) => resp.json())
.then((data) =>
data.success ? alert("Product Deleted") : alert("Failed to delete product")
);

// Refresh the product list


setProducts(products.filter((product) => product._id !== selectedProduct));
setSelectedProduct(""); // Clear the selection after deletion
};

return (
<div className="deleteproduct">
<div className="deleteproduct-itemfield">
<p>Select Product to Delete</p>
<select
value={selectedProduct}
onChange={(e) => setSelectedProduct(e.target.value)}
className="delete-product-selector"
>
<option value="">Select a product</option>
{products.map((product) => (
<option key={product._id} value={product._id}>
{product.name}
</option>
))}
</select>
</div>
<button className="deleteproduct-btn" onClick={deleteProduct}>
DELETE
</button>
</div>
);
};

export default DeleteProduct;

You might also like