Search code examples
reactjssetstate

setState not merging but replacing


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


Solution

  • 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 
      }}
    }));