0

I have a cart. When adding a product it is having trouble for it to properly check if the same shoe and size already exists then to add it towards the quantity. For example Starting with an empty cart, I add a shoe to cart of size 8 with a quantity of 3. Works fine. Then when adding the same shoe with a different size and quantity will not create a new product in the cart instead will update the previously added product to cart instance of a new size and quantity. For some reason when trying a third time to add the same product with a different size and quantity properly works as intended an will create a new product in the cart.

Here i am using contextAPI and useReducer.

  case ADD_TO_CART:
      if (
        state.cart.find((product) => product.key === payload.key) &&
        state.cart.find(
          (product) => product.selectedSize === payload.selectedSize
        )
      ) {
        return {
          ...state,
          cart: state.cart.map((product) =>
            product.key === payload.key &&
            product.selectedSize === payload.selectedSize
              ? {
                  ...product,
                  // set item quantity to sum of current quantity in cart and new payload quantity.
                  quantity: Number(product.quantity) + Number(payload.quantity),
                }
              : product
          ),
        };
      } else {
        return {
          ...state,
          cart: [...state.cart, payload],
        };
      }

I cannot seem to get it to properly check if the product already exists with the same shoe size. If so i want it to add to existing quantity. If it doesnt then create a new product in the cart.

pNut
  • 21
  • 5

1 Answers1

0

I guess this could work:

const existingProductIndex = state.cart.findIndex(
    ({ key, selectedSize }) => key === payload.key && selectedSize === payload.selectedSize
)

if (!existingProductIndex) return { ...state, cart: [...state.cart, payload] }

const updatedCart = [...state.cart]

updatedCart[existingProductIndex] = {
    ...updatedCart[existingProductIndex],
    quantity: Number(product.quantity) + Number(payload.quantity),
}

return { ...state, cart: updatedCart }
maxpsz
  • 431
  • 3
  • 9