Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update nested state properties in React

I'm trying to organize my state by using nested property like this:

this.state = {    someProperty: {       flag:true    } } 

But updating state like this,

this.setState({ someProperty.flag: false }); 

doesn't work. How can this be done correctly?

like image 470
Alex Yong Avatar asked Mar 27 '17 07:03

Alex Yong


People also ask

How do you update nested objects in state React?

To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.

How do you update part of state in React?

To update our state, we use this. setState() and pass in an object. This object will get merged with the current state. When the state has been updated, our component re-renders automatically.

How do you access nested objects in React?

If we want to access all the values of nested objects then we have to use recursion to access each and every level of that object. And it can get more complicated according to the nesting of the object. That why we have to use recursion to get all the values and access the whole nested object.


2 Answers

In order to setState for a nested object you can follow the below approach as I think setState doesn't handle nested updates.

var someProperty = {...this.state.someProperty} someProperty.flag = true; this.setState({someProperty}) 

The idea is to create a dummy object perform operations on it and then replace the component's state with the updated object

Now, the spread operator creates only one level nested copy of the object. If your state is highly nested like:

this.state = {    someProperty: {       someOtherProperty: {           anotherProperty: {              flag: true           }           ..       }       ...    }    ... } 

You could setState using spread operator at each level like

this.setState(prevState => ({     ...prevState,     someProperty: {         ...prevState.someProperty,         someOtherProperty: {             ...prevState.someProperty.someOtherProperty,              anotherProperty: {                ...prevState.someProperty.someOtherProperty.anotherProperty,                flag: false             }         }     } })) 

However the above syntax get every ugly as the state becomes more and more nested and hence I recommend you to use immutability-helper package to update the state.

See this answer on how to update state with immutability-helper.

like image 60
Shubham Khatri Avatar answered Oct 16 '22 22:10

Shubham Khatri


To write it in one line

this.setState({ someProperty: { ...this.state.someProperty, flag: false} }); 
like image 30
Yoseph Avatar answered Oct 16 '22 20:10

Yoseph