1

Initial state of react redux.

reducer.js

cart {
  id: 100,
  name: "Pizza",
  price: 550,
  category: "Fasting",
  time: "20-50 min",
  restaurantId: "BH001",
  quantity: 1,
  photo: {
    fileName: "",
    fileType: "",
    filePath: "",
  },
  description:"The food is ...",
},

What I did to update quantity element.

case "INCREASE_DECREASE_ORDER_AMOUNT":
  return {
    ...state,
    carts: [
      ...state.cart.map((val) => {
        if (val.id === action.payload) {
          if (action.typo == "+") {
            return {
              ...val,
              quantity: val.quantity + 1,
            };
          }
        }
      }),
    ],
  };

The action of react redux.

action.js

const increaseDeacreaseOrderAmount = (id, typo) => {
  return {
    type: "INCREASE_DECREASE_ORDER_AMOUNT",
    payload: id,
    typo: typo,
  };
};

export { increaseDeacreaseOrderAmount }

index.js

onPress={() => {
  dispatch(increaseDeacreaseOrderAmount(value.id, "+"));
}}

The problem is quantity in reducer isn't updating.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181

2 Answers2

0

The INCREASE_DECREASE_ORDER_AMOUNT reducer case appears mostly correct, in that it is correctly shallow copying the state it is updating. The issue I see is that it doesn't return defined state.cart items for the items it is not updating. Array.prototype.map should return a value for each element of the array it is operating over.

case "INCREASE_DECREASE_ORDER_AMOUNT":
  return {
    ...state,
    carts: [
      ...state.cart.map((item) => {
        if (item.id === action.payload) {
          if (action.typo == "+") {
            return {
              ...item,
              quantity: item.quantity + 1,
            };
          }
        }

        // return un-updated cart item
        return item;
      }),
    ],
  };
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
0

Finnay I get it.

 case "INCREASE_DECREASE_ORDER_AMOUNT":
      return {
        ...state,
        carts: [
          ...state.cart.map((item) => {
            if (item.id === action.payload) {
              if (action.typo == "+") {
                return {
                  ...(item.quantity = item.quantity + 1),
                };
              }
            }
          }),
        ],
      };
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 27 '23 at 12:42