Search code examples
reactjsreduxreact-reduxredux-toolkit

How can i change the value of an element in an object from extrareducer redux


This is the initial state:

const initialState ={
  ordersWholesale:[
    {
      "id": 14,
      "name": "XTPara 650mg Tablet",
      "code": "XTP5656",
      "date": "17/10/2022",
      "accepted": null,
      "wholesale": "shakthi",
      "quantity": "5"
    },
    {
      "id": 15,
      "name": "Dolo 650 Tablet",
      "code": "DOL1213",
      "date": "17/10/2022",
      "accepted": false,
      "wholesale": "shakthi",
      "quantity": "5"
    },
  ],
}

This is the slice reducer

extraReducer: {
  [asyncOrderAccept.fulfilled]: (state, { payload }) => {

  }
}

How can I change only the value orderWholesale[0]['accepted']: true using the payload value which is 14?


Solution

  • If I'm understanding your question correctly that the action payload is the id of the ordersWholesale state element you want to toggle true, then you'll need to search the array to find the correct element by id and then update that element. Keep in mind that state is the ordersWholesale array and that Array.prototype.find potentially returns undefined if no match is found.

    extraReducer: {
      [asyncOrderAccept.fulfilled]: (state, { payload }) => {
        const el = state.find(order => order.id === payload);
        if (el) {
          el.accepted: true,
        }
      },
    }
    

    This may also work for you if you can use Optional Chaining.

    extraReducer: {
      [asyncOrderAccept.fulfilled]: (state, { payload }) => {
        state.find(order => order.id === payload)?.accepted = true;
      },
    }