I am building a warehouse management site. I have the data stored in MongoDB. I want the product quantity to be updated on a button click and show it on the UI. But after updating the quantity, when I console log it I get undefined.
This is the function to decrease the quantity on click and update it on DB:
const ProductDetail = () => {
const { productId } = useParams();
const [product] = useProductDetail(productId);
const { _id, name, img, description, supplier, price, quantity } = product;
const [updatedQuantity, setUpdatedQuantity] = useState(quantity);
const handleDecreaseQuantity = (id) => {
const { quantity, ...rest } = product;
const previousQuantity = quantity;
setUpdatedQuantity(previousQuantity - 1)
const updatedProduct = { updatedQuantity, ...rest }
fetch(`http://localhost:5000/updateProduct/${id}`, {
method: 'PUT',
headers: {
"content-type": "application/json"
},
body: JSON.stringify(updatedProduct)
})
.then(res => res.json())
.then(data => {
console.log(data)
})
console.log(updatedQuantity);
}
This is product update API:
app.put('/updateProduct/:id', async (req, res) => {
const updatedProduct = req.body;
const { updatedQuantity } = updatedProduct;
const id = req.params.id;
const query = { _id: ObjectId(id) };
const options = { upsert: true };
const updateProduct = {
$set: {
quantity: updatedQuantity
},
};
const result = await productCollection.updateOne(query, updateProduct, options);
console.log(result);
res.send(result);
})
setState actions are asynchronous and are batched for performance gains. This is explained in the documentation of setState.
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
This part of the code might not be executing as you think.
const previousQuantity = quantity;
setUpdatedQuantity(previousQuantity - 1);
const updatedProduct = { updatedQuantity, ...rest };
Update your product quantity and send it to API. By the action is completed, your state also might be updated.
const previousQuantity = quantity;
const updatedProduct = { updatedQuantity: previousQuantity - 1, ...rest };
setUpdatedQuantity(previousQuantity - 1);