-
-
Notifications
You must be signed in to change notification settings - Fork 657
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
if i try to add same item after adding another item it says undefiend to all the other items beside newly added one #109
Comments
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 :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
);};
The text was updated successfully, but these errors were encountered: