0

I have a problem increasing and decreasing the number of products in the cart of only the targeted product using the use-reducer in React. When ever i click on the increase or decrease button, i recieve error and the entire display disappear

Here is my reducer function:

 if (action.type === "INCREASE_QUANTITY") {
    return {
      ...state,
      cart: state.cart.map((x) =>
        x.id === action.payload ? x.quantity + 1 : x.quantity
      ),
    };
  }

  if (action.type === "DECREASE_QUANTITY") {
    {
      return {
        ...state,
        cart: state.cart.map((x) =>
          x.id === action.payload ? x.quantity - 1 : x.quantity
        ),
      };
    }
  }

And this is my dispatch function:

  const increaseQuanity = (id) => {
    dispatch({ type: "INCREASE_QUANTITY", payload: id });
  };
  const decreaseQuanity = (id) => {
    dispatch({ type: "DECREASE_QUANTITY", payload: id });
  };

And finally, this is the button, which calls the function:

<div className="flex space-x-2 md:space-x-3 items-end mt-4 md:mt-9 md:text-xl">
                    <button
                      onClick={() => decreaseQuanity(item)}
                      className=" font-bold text-yellow-700 shadow p-2 border-1 rounded-md  ">
                      <FaMinus />
                    </button>
                    <h3 className="text-2xl ">{item.quantity}</h3>

                    <button
                      onClick={() => increaseQuanity(item)}
                      className=" font-bold text-yellow-700 shadow p-2 border-1 rounded-md  ">
                      <FaPlus />
                    </button>
                  </div>

Please, I really need help. Thanks!

Rengkat
  • 23
  • 8

1 Answers1

1

Your increaseQuantity and decreaseQuantity functions are expecting to receive an id, which I assume should be a string.

const increaseQuanity = (id) => {
    dispatch({ type: "INCREASE_QUANTITY", payload: id });
  };
  const decreaseQuanity = (id) => {
    dispatch({ type: "DECREASE_QUANTITY", payload: id });
  };

But when you are executing then you are passing an item object.

Fix to reducers

if (action.type === "INCREASE_QUANTITY") {
    return {
      ...state,
      cart: state.cart.map((x) =>
        x.id === action.payload 
          ? ({...x, quantity: x.quantity + 1 })
          : x
      ),
    };
  }
Mariusz Bartnik
  • 356
  • 1
  • 6