2

I have some state

  state = {
    theme: {
      background: { bgType: 'colour', value: '#449dc7' },
      primary: '#4d5a66',
      secondary: '#476480',
    },
  };

When I try and update a nested property such as background I call setState as follows

this.setState(prevState => ({
  ...prevState,
  theme: { background: { bgType: 'colour', value: color.hex } },
}));

This however just replaces the state with

  theme: { background: { bgType: 'colour', value: color.hex } },

I lose the other properties

Harry Blue
  • 4,202
  • 10
  • 39
  • 78
  • its because you are assigning the new value to theme, instead of merging the old values and new value. Update it like this: `theme: { ...prevState.theme, background: { bgType: 'colour', value: color.hex } },` – Mayank Shukla Jun 25 '18 at 19:11

3 Answers3

1

If you want to set only background properly in theme, you need to use spread syntax with theme and not state like

this.setState(prevState => ({
  theme: { ...prevState.theme, background: { bgType: 'colour', value: color.hex } }
}));

In case you want to merge the background values too, you need to spread it too like

this.setState(prevState => ({
  theme: { ...prevState.theme, background: { 
      ...prevState.theme.background, 
      bgType: 'colour', value: color.hex 
  }}
}));
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • For a true deep merge he should spread the state.theme.background obj as well – Danny Delott Jun 25 '18 at 19:07
  • @DannyDelott, as mentioned in the OP case, he seems to have not been merging background value and hence I decided to omit that part. But sure will add that portion in my answer too – Shubham Khatri Jun 25 '18 at 19:09
0

Spread the inner objects as well:

this.setState(prevState => ({
  ...prevState,
  theme: { 
    ...prevState.theme,
    background: { 
      ...prevState.theme.background,
      bgType: 'colour', value: color.hex
    }
  },
}));
Danny Delott
  • 6,756
  • 3
  • 33
  • 57
0

You have to spread the theme object:

this.setState(({ theme }) => {
  return { theme: { ...theme, background: { bgType: 'colour', value: color.hex } } };
});
Tholle
  • 108,070
  • 19
  • 198
  • 189