ecommerce_sanity_stripe
ecommerce_sanity_stripe copied to clipboard
UNABLE TO OPEN CART AFTER ADDING EXISTING CART ITEM AGAIN.
Lets say I add ItemA , ItemB or ItenC.... Cart works just fine. Lets say i add ItemA or ItemB (existing cart item) again. Cart Icon shows increase in number of cart items. But if I click on cart icon I get the below error. The code is same as adrian.
@TheCodePoetChick
I was having this same issue and started messing around with the StateContext.js and found that adding the product.quantity and quantity together should have actually been the item.quantity and quantity being added together.
Here is the updated addToCart function from the StateContext.js:
const addToCart = (product, quantity) => {
const checkProductInCart = cartItems.find(
(item) => item._id === product._id
);
if (checkProductInCart) {
const updatedCartItems = cartItems.map((item) => {
if (item._id === product._id) {
const newQty = item.quantity + quantity;
return {
...item,
quantity: newQty,
};
} else {
return {
...item,
};
}
});
setCartItems(updatedCartItems);
localStorage.setItem("cart", JSON.stringify(updatedCartItems));
} else {
product.quantity = quantity;
setCartItems([...cartItems, { ...product }]);
localStorage.setItem(
"cart",
JSON.stringify([...cartItems, { ...product }])
);
}
setTotalPrice(
(prevTotalPrice) => prevTotalPrice + product.price * quantity
);
setTotalQuantities((prevTotalQuantities) => prevTotalQuantities + quantity);
toast.success(`${qty} ${product.name} added to cart.`);
};
};
@miahthegreat Thanks very much this really helped who knew just this one line of code could be so much problem, i guess i still have a lot to learn 😂
@miahthegreat Thanks Man, the nested "else" part was missing in my code. After adding the "else" part from your code, it worked. else { return { ...item, }; }
can you explain why that else part run code correctly?
can you explain why that else part run code correctly?
Because it has to return the item into updatedCartItems when the item being added doesn’t already exist in the cart.