skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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),
                    };
                  }
                }
              }),
            ],
          };
    

  2. 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;
          }),
        ],
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search