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
Now if we want to update value5 to a new value, we cannot do like below
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
2. Creating Deep Copy of Object
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.
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.
Related articles
- How to create Simple Twitter Bot in Node.js
- Legacy Browser Support for using Babel
- Getting Started with Node.js Koa 2 Framework
- Web Scraping Libraries for Node.js Developers
- How to Create Simple RSS Reader in Ionic Application
- Simple RESTful API in Nodejs
- How to Get Latest Tweets of a particular HashTag using Nodejs
- How to Intercept HTTP requests in Node.js
- Node for Android
- Capture Screen of Web Pages through URL in Nodejs
No comments:
Post a Comment