adrianhajdin / ecommerce_sanity_stripe

Modern Full Stack ECommerce Application with Stripe
https://jsmastery.pro
2.21k stars 675 forks source link

if i try to add same item after adding another item it says undefiend to all the other items beside newly added one #109

Open IsuruWickramasinghe opened 1 year ago

IsuruWickramasinghe commented 1 year ago

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.); };

KD-Long commented 8 months 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 :)