adrianhajdin / ecommerce_sanity_stripe

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

UNABLE TO OPEN CART AFTER ADDING EXISTING CART ITEM AGAIN. #9

Open TheCodePoetChick opened 2 years ago

TheCodePoetChick commented 2 years ago

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.

Screenshot from 2022-04-30 14-29-42

Screenshot from 2022-04-30 14-34-59

miahthegreat commented 2 years ago

@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.`);
  };
  };
heep-jay commented 2 years ago

@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 😂

Aditya123621 commented 1 year ago

@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, }; }

OmJadhav1 commented 1 year ago

can you explain why that else part run code correctly?

miahthegreat commented 1 year ago

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.