javascriptreactjsreduxshopping-cartreducers

Add same product with different sizes to the cart


I can add different products as individual arrays and also can increment the quantities if same product is added. But now I need to add same product but with Different size and it should create another new array. Below is the code I am using.. Please help out..!!

switch (action.type) {
case ADD_TO_CART:
    const productId = action.product.id;

    if (findIndex(state.cart, product => product.id === productId) !== -1) {
        const cart = state.cart.reduce((cartAcc, product) => {
            if (product.id === productId) {
                // if (product.size === action.size) {
                    cartAcc.push({ ...product, size: parseInt(product.size), qty: parseInt(product.qty) + parseInt(action.qty), sum: (product.discount ? product.salePrice : product.price) * (parseInt(product.qty) + parseInt(action.qty)) }) // Increment qty
                // } else {
                //     cartAcc.push(product)
                // }

            } else {
                cartAcc.push(product)
            }
            return cartAcc
        }, [])

        return { ...state, cart }
    }
    return {
        ...state,
        cart: [
            ...state.cart,
            {
                ...action.product,
                qty: action.qty,
                size: action.size,
                sum: (action.product.discount ? action.product.salePrice : action.product.price) * action.qty
            }
        ]
    }

Solution

  • Your code is correct however you need to give a unique product ID for each product with specific attributes. for Example

    Product: { id: 'Nike' size: ['S', 'M', 'L'] color: ['blue', 'white', 'black']}

    your Cart is having multi items where this product example having ID: 'Nike,s,blue'. each time you try to find this product with that specific ID you will be able to add it as new or Increase it if it already exist.

    You may take the same logic with T-shirt 'L' where its ID: 'Nike,L,blue'. it make it a new product and separated.

    Briefly: You need to make a unique ID for each product along with its Attributes (you may combine the attributes with the ID based on the Object.values or array where you have the Data).