Why onClick run TWICE/ Why Array.map() vs Array.filter() returned different result


I have some questions while doing the Shopping Cart project.

github link

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(),

      console.log("Increase Qty");
      const tempCart = state.cart.map((item) => {
        if (item.id === action.payload) {
          return { ...item, amount: item.amount + 1 };
        return item;
      return {
        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())

      console.log("Increase Qty");
      return {
        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:

i found the solution here if anyone is interested,
array.filter is good for finding a item that match the criteria, if using it to updated data, it will not only modifying the original item but also the item in the new return array, so the item will be updated twice at the end.
on the other hand, array.map is the best choice to modify data, it return a new array and modify the data in the new array, not the original array/object.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.