Home > Mobile >  Problem checking if an item exists in cart
Problem checking if an item exists in cart

Time:09-13

hello I've been having a problem with checking if an item already exists in the cart. if so I want only the quantity to be updated for some reason it keeps adding the item as a new item even if it exists. This is what I've been doing:

  // Adding Items to cart
  const onAdd = (product, quantity) => {
  const checkProductInCart = cartItemsFromLocalStorage.find((item) => item.id === product.id);

  setTotalPrice((prevTotalPrice) => (prevTotalPrice   Math.round((product.price * quantity)*100)/100));
  setTotalQuantities((prevTotalQuantities) => prevTotalQuantities   quantity);


 if(checkProductInCart) {
   // eslint-disable-next-line
  const updatedCartItems = cartItemsFromLocalStorage.map((cartProduct) => {
    if(cartProduct.id === product.id) return {
      ...cartProduct,
      quantity: cartProduct.quantity   quantity
    }
    
  })

  setCartItems(updatedCartItems);
} else {
  product.quantity = quantity;
  

  setCartItems([{ ...product }, ...cartItems]);
}

toast.success(` ${product.name} added to the cart.`);

}

CodePudding user response:

Seems like the issue is on your cartItemsFromLocalStorage.map implementation. The map function should return the product even if it isn't the one you're looking to update. Try updating that map to

cartItemsFromLocalStorage.map((productOnCart) => {
  if (productOnCart.id === product.id) {
    return { ...productOnCart, cartProduct.quantity   quantity }
  }
  return productOnCart
})

If you don't return anything your list will be full of undefined objects

  • Related