How can I not have duplicate value in shopping cart made with react using Context API? Code Answer

This is the code that I used in the reducer to add items to cart, the return statement below is what I was trying to use to not allow any duplicate items in the cart but to change only the quantity of the item. But it still did not work. The quantity does update but I still end up with duplicate values. So please help me figure this out, Thx

export const initialState = {
    cart: []
}

const Reducer = (state = initialState, action) =>{
    switch(action.type){
        case "ADD_TO_CART":
            const {id, quantity} = action.item
            let alreadyInCart = false, newQty=0
            
            state.cart.forEach(x =>{
                if(x.id === id){
                    alreadyInCart = true
                    newQty = parseInt(x.quantity+quantity)
                }
            })

            //let categories = [...new Set(Inventory.map(x=>x.category))]

            if(!alreadyInCart){
                return {
                    ...state,
                    cart: [...state.cart, action.item]
                }
            } else{
           ***return {
                  ...state,
                   cart: [...state.cart, 
                       {...action.item, quantity: newQty}
                   ]
               }***
            }
        default:
            return state
    }
}

export default Reducer

Answer

Looks like you just need to update the existing item in the cart, or add it to the cart.

Try this.

export const initialState = {
  cart: [],
};

const Reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_TO_CART':
      const nextCart = [...state.cart];
      const existingIndex = nextCart.findIndex((item) => item.id === action.item.id);

      if (existingIndex >= 0) {
        const newQuantity = parseInt(nextCart[existingIndex].quantity + action.item.quantity);

        nextCart[existingIndex] = {
          ...action.item,
          quantity: newQuantity,
        };
      } else {
        nextCart.push(action.item);
      }

      return {
        ...state,
        cart: nextCart,
      };
    default:
      return state;
  }
};

export default Reducer;

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji