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,
            }

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes I set the parenthesis wrong. The forEach needs to stop after the first if-clause.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.