Reputation: 133
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,
}
Upvotes: 0
Views: 32
Reputation: 1222
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
}
Upvotes: 1