1

I am facing an issue with the shopping cart. After clicking on INCREASE_QTY to increase the quantity of an existing item in the cart, It increases two instead of one. Total item quantity increase correctly but single item quantity now increases correctly. I am using React useReducer hook with context API.

 case "ADD_TO_CART":
      if (state.cart.length === 5) {
        return state;
      } else {
        items = action.item;
        items["itemQty"] = 1;   // add single item qty in array 
        updateQty = state.qty + 1; // total items qty
        items["day"] = action.dayItem;
        return {
          cart: [items, ...state.cart],
          qty: updateQty,
        };
      }
    case "INCREMENT_QTY":
      items = action.item;
      items.itemQty = items.itemQty + 1
      updateQty = state.qty + 1
      index = state.cart.findIndex((cart) => cart.id === action.id);
      state.cart[index] = items;
      return {
        cart: [...state.cart],
        qty: updateQty,
      }

I am getting quantity 2 after clicking once. How I can solve this issue

Adil Rao
  • 19
  • 1

1 Answers1

0

Take a look at the React docs here for how to implement a Reducer Hook with Context.
https://reactjs.org/docs/hooks-reference.html#usereducer (the React example from the docs outlines how to achieve your specific goal above.

Here's another great resource for using context with a custom hook for Auth that may make the React pattern a little easier to understand at a higher level that helped me. https://fatmali.medium.com/use-context-and-custom-hooks-to-share-user-state-across-your-react-app-ad7476baaf32