what problem my code ?
I actually want to reduce and increase the quantity of some items from one button but I can't understand what is wrong with the code. So I'm here to help. Please help anyone. Thank you
**server side**
** PUT METHODS**
app.put("/items/:id", async (req, res) => {
const id = req.params.id;
const updateItemData = req.body;
const filter = { _id: ObjectId(id) };
const option = { upsert: true };
const updateItemDoc = {
$set: {
quantity: updateItemData.itemQuantity,
},
};
const result = await itemsCollection.updateOne(
filter,
option,
updateItemDoc
);
res.send(result);
});
} finally {
}
};
**client side**`enter code here`
useEffect(() => {
fetch(`http://localhost:5000/items/${itemId}`)
.then((response) => response.json())
.then((data) => setItem(data));
}, []);
const handleItemDelivered = (quantity) => {
const newQuantity = item.quantity - 1;
console.log(newQuantity);
const { itemQuantity } = newQuantity;
console.log(parseInt(newQuantity));
const url = `http://localhost:5000/items/${itemId}`;
fetch(url, {
method: "PUT",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(itemQuantity),
})
.then((response) => response.json())
.then((datenter code herea) => setItem(data));
alert("quantity-updated successfully");
};
CodePudding user response:
Since you are increasing and decreasing the count, the best practice is to use $inc
instead of $set
. This is an atomic operation that will allow you update from several clients "on parallel", i.e., they will not override each-other:
const updateItemDoc = {
$inc: {
quantity: updateItemData.deltaQuantity,
},
};