Open IsuruWickramasinghe opened 1 year ago
Same issue. I suspect something is not working as expected when we are updating the quantity of the matching item. Instead of replacing it with the same item with an updated quantity it is updating it with undefined.
I replaced:
if(checkProductInCart) {
const updatedCartItems = cartItems.map((cartProduct) => {
if(cartProduct._id === product._id) return {
...cartProduct,
quantity: cartProduct.quantity + quantity
}
})
setCartItems(updatedCartItems);
}
With:
if (checkProductInCart) {
// find the index
index = cartItems.findIndex((item) => item._id === product._id)
//shallow copy
let newCartItems = [...cartItems]
//update the item
checkProductInCart.quantity += quantity
//insert back into the same place
newCartItems[index] = { ...checkProductInCart }
//update
setCartItems(newCartItems)
}
And it seems to be working correctly :)
const onAdd = (product, quantity) => { const checkProductInCart = cartItems.find((item) => item._id === product._id);
settotalPrice((prevTotalPrice) => prevTotalPrice + product.price * quantity); settotalQuantities((prevTotalQuantities) => prevTotalQuantities + quantity);
if (checkProductInCart) { const updatedCartItems = cartItems.map((cartProduct) => { if (cartProduct._id === product._id) { return { ...cartProduct, quantity: cartProduct.quantity + quantity }; } return cartProduct; // Add this return statement }); setcartItems(updatedCartItems); } else { product.quantity = quantity; setcartItems([...cartItems, { ...product }]); }
toast.success(
${selectedQuantities} ${product.name} added to the cart.
); };