Hi,
I have some questions while doing the Shopping Cart project.
Can someone please explain why onClick function run twice but the value of Qty was updated only 1 time?
the console showed onClick triggered 2 times, but the qty only increased by one as I clicked 1 time only
the tutorial code is using Array.map()
,
case "INCREASE_QTY":
console.log("Increase Qty");
const tempCart = state.cart.map((item) => {
if (item.id === action.payload) {
return { ...item, amount: item.amount + 1 };
}
return item;
});
return {
...state,
cart: tempCart,
};
But when I used Array.filter()
, the onClick run twice and the Qty increased by 2, (not 1 compared to using Array.map()
)
case "INCREASE_QTY":
console.log("Increase Qty");
return {
...state,
cart: state.cart.filter((item) =>
item.id === action.payload ? (item.amount += 1) : item
),
};
does it mean i can not use Array.filter() here?
if i remove Strict Mode
, it looks like solved the problem of running function 2 times, but it is not a good idea right?
Here is the project tutorial link: