2

I want to update a state value where the key is also dynamic in redux reducer, but I tried various method I am not able to do it.

So my Initial State looks like this

const initalState = {
ingredients:{
  bacon:0,
  salad:0,
  cheese:0,
  meat:0,
},
price:100
};

And my data passed in reducer looks like this

{type: "INCREASEQUANTITY", payload: {
item: "bacon",
value: 1
}}

And I want result state looks like

const initalState = {
ingredients:{
  bacon:1, //updated value
  salad:0,
  cheese:0,
  meat:0,
},
price:100
};

I tried to update it immutably, but its showing syntax error. My code for this looks like this

      return{
    ...state,
    state.ingredients:{
      ...state.ingredients,
      action.payload.item:state.ingredients[action.payload.item]+action.payload.value //this line explained below
    }
  }

I want to update it with key and value both dynamically like bacon:0+1 but getting syntax issue.

Please help.Thank you

1 Answers1

1

You were on the right track

return {
  ...state,
  ingridients: {
     ...state.ingridients,
     [action.payload.item]: state.ingredients[action.payload.item] + action.payload.value
  }
}
k.s.
  • 2,964
  • 1
  • 25
  • 27
  • Yes, this solution worked for me. Thanks. I just want to ask `ingredients` here you don't add state but here `[action.payload.item]: state.ingredients[action.payload.item] + action.payload.value` we use `state.ingredients` – mathur.prerit Jun 22 '20 at 14:42
  • 1
    because you are returning a new object, and you need to define its new structure, but in order to not break anything - we define the same structure as in the `initialState`. So if it's was an object on initial, we need to make it an object now too – k.s. Jun 22 '20 at 14:45