reactjsreact-state

If exists increase count else add new product to cart


I have created a cart which I'm able to add products to and that works fine, however I'm trying to adapt it now so if you try to add a product that already exists in the cart (it checks if a matching product ID exists in a useState array) it will not add the product to the cart again but increase the quantity value.

Although I've got most of the way there and my below code does actually increase the product quantity (if it exists), it's also adding a blank item to the cart array as well and I'm racking my brains a bit too much trying to stop it unsuccessfully.

Here's my most recent code and what's happening visually when adding the same product to the cart more than once:

const addToCart = (productID, productBrand, productTitle, productPrice, productQuantity, productThumbnail) => {
  const checkProdtExists = props.cartProducts.find(product => product.productID == productID);
  if (checkProdtExists) {
    props.setCartProducts(prevProduct => [...prevProduct, checkProdtExists.productQuantity++]);
  } else {
    props.setCartProducts(prevProduct => [
      ...prevProduct,
      {
        productID: productID,
        productBrand: productBrand,
        productTitle: productTitle,
        productPrice: productPrice,
        productQuantity: productQuantity,
        productThumbnail: productThumbnail
      }
    ])
  }
}

Adding the product once:

first product added

Adding the same product a second time:

second time added

Any help on what the issue and solution is? would be much appreciated, thanks


Solution

  • Issue Lies Here

    props.setCartProducts(prevProduct 
    => [...prevProduct, checkProdtExists.productQuantity++]);
    

    //the above adds an incremented value of productQuantity as a new item as it returns a new value before it adds it.

    //findProductByIndex -method checks if a product with the specified productID exists in the cart.
    const checkProdExistsByIndex = 
      props.cartProducts.findIndex(product => product.productID == productID);
    
      if (checkProdExistsByIndex != -1) {
       props.setCartProducts(prevProduct => {
         const productsNeedsToBeUpdated = [...prevProduct] // get the product need to be updated 
        productsNeedsToBeUpdated[checkProdExistsByIndex].productQuantity += productQuantity
        // get the product quantity of the product and update it
         return productsNeedsToBeUpdated
       });
      } else {
        // If the product does not exist, add a new one to the cart
        props.setCartProducts(prevProduct => [
          ...prevProduct,
          {
            productID: productID,
            productBrand: productBrand,
            productTitle: productTitle,
            productPrice: productPrice,
            productQuantity: productQuantity,
            productThumbnail: productThumbnail
          }
        ])
      }
    }
    

    Hope this Helps!..