Updating state for a value inside an object immutably in redux reducers

Viewed 24

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 Answers

You were on the right track

return {
  ...state,
  ingridients: {
     ...state.ingridients,
     [action.payload.item]: state.ingredients[action.payload.item] + action.payload.value
  }
}
Related