My Delete API is http://localhost:8080/api/inventory/deleteproduct
with the request body in JSON format:
{
"upc": "100101101111"
}
upc is the unique value for each product.
Here is my code for fetching data from API:
export function Inventory() {
const [product, setProduct] = useState(null);
useEffect(() => {
axios
.get("http://localhost:8080/api/inventory/products")
.then((response) => {
setProduct(response.data);
});
}, [url]);
if (product) {
return (
<div>
<h1>Inventory</h1>
<table className="table">
<thead>
<tr>
<th scope="col">Product Name</th>
<th scope="col">Brand</th>
<th scope="col">Category</th>
<th scope="col">Product Description</th>
<th scope="col">Price Per Unit</th>
<th scope="col">Available Stock</th>
<th scope="col">Reserved Stock</th>
<th scope="col">Shipped Stock</th>
<th scope="col">Image</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{product.map((item) => (
<tr>
<td>{item.productName}</td>
<td>{item.brand}</td>
<td>{item.category}</td>
<td>{item.productDescription}</td>
<td>{item.pricePerUnit}</td>
<td>{item.availableStock}</td>
<td>{item.reservedStock}</td>
<td>{item.shippedStock}</td>
<td>
<img src={item.imageUrl} height={100} width={100} />
</td>
<td>
<Button>
onClick={() => {
onDeleteProduct();
}}
style={{ color: "red", marginLeft: 12 }}
/Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
I've already done the part of GET method to fetch all the data from API to the table.
Now I'm working on the DELETE method. I've also already created a delete button in each row. But I have no idea how to get the upc
value in the row that I click the delete button to call an API http://localhost:8080/api/inventory/deleteproduct
.
Can someone give me some idea, please?
CodePudding user response:
Since each item has a unique upc
, then your function should accept this as an argument
<td>
<Button>
onClick={() => {
onDeleteProduct(item.upc);
}}
style={{ color: "red", marginLeft: 12 }}
/Button>
</td>
and then your method would become like this
onDeleteProduct = itemUpc => {
axios.delete('http://localhost:8080/api/inventory/deleteproduct', { data: { upc: itemUpc }, headers: { } });
}