0

I have this one case in the reducer function where I want to push an object (that is the payload) to the items array. I saw it in a video and change some code. But now it doesn't work as it should and doesn't push the object into the array. Here is the case:

case "ADD_ITEM_CART":
            const cartItems = state.items.slice();
            const tempItem = action.payload;
            let alreadyExists = false;
            cartItems.forEach((x)=>{
                if(x._id === action.payload._id){
                    alreadyExists = true;
                    x.count++;
                }
                if(!alreadyExists){
                    cartItems.push({...tempItem,count:1})
                }
            });
            localStorage.setItem("cartItems",JSON.stringify(cartItems));
            return{
                ...state,
                items: cartItems,
            }
devGuy
  • 113
  • 1
  • 9

1 Answers1

1

That's because alreadyExists is always true after first existed card appears because it is outside of forEach.

You should back it to false after some existed card:

if(!alreadyExists){
  cartItems.push({...tempItem,count:1})
  alreadyExists = false
  break
}
QuazBuzz
  • 1,112
  • 1
  • 8
  • 18