Problems in deleting an item in ReactJS and MongoDB

Viewed 27

I am building an inventory project using ReactJS, ExpressJS and MongoDB, which is basically an CRUD project. My project working perfectly for all operations except the Delete. When I want to delete an item, my project can delete an item but it always deletes the first item of the list. Whenever I tried to delete other items except First Item it always deletes the first item

Here I am giving my Client Side Code:

const handleDelete = (id) => {
    const url = `http://localhost:5000/inventory/${id}`;
    fetch(url, {
      method: "DELETE",
    })
      .then((res) => res.json())
      .then((data) => {
        const remaining = products.filter((product) => product._id !== id);
        setProducts(remaining);
      });
  };

I have sent this function as a props in my SingleItem Component and added it as an eventHandler

Here I am giving eventHandler Code:

<button onClick={() => handleDelete(_id)} type="button">
   Delete
</button>

Now I'm giving my Server side code:

app.delete("/inventory/:id", async (req, res) => {
      const id = req.params.id;
      const query = { _id: ObjectId(id) };
      const result = await productCollection.deleteOne(query);
      res.send(result);
});

0 Answers
Related