a blog for those who code

Saturday 20 October 2018

How to Update Object in setState in React

In this post we will be discussing how to update object in setState in React.js. A React Component can have an initial state which will be like a JSON but the main problem comes in when we tried to update it. We mainly use setState() function to update the state of the component.


Let's say we have something like below

{
  value1: '1'
  value2: {
    value3: '3',
    value4: '4',
    value5: '5',
    value6: '6',
  },
}

Now if we want to update value5 to a new value, we cannot do like below

this.setState({
  value2: {
    value5: '50',
  },
});

This is because setState only merges on the first level and not deeply merge the object and the object will get overwritten. Now if we need to update it we have two methods

1. Using Spread Operator

this.setState(prevState => ({
    value2: {
        ...prevState.value2,
        value5: '50'
    }
}))

2. Creating Deep Copy of Object

let value2 = {...this.state.value2};
value2.value5 = '50';
this.setState({value2});

In this way you can actually update the whole object.

Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a Comment