Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update nested setState Object - ReactJS

this.state = {
    qs: {catName:'',subCatName:''}
}

I have the above nested state object. In order to setState, I used the below code in componentDidUpdate.

var newQs = {...this.state.qs}
newQs.catName = 'name';
this.setState({qs: newQs});

But it does not working, still this.state.qs is empty not updated. I even tried the following one.

this.setState({...this.state, qs: {
    ...this.state.qs,
    catName: 'name'
}});

Still not works.

like image 303
Anand Ram Avatar asked Aug 20 '26 02:08

Anand Ram


1 Answers

Use setState like this:

this.setState( prevState =>
    ( { qs: { ...prevState.qs, catName: 'name' } } )
)

You don't need here ...this.state since React merges other parts of your state.

Also I edited my suggestion according to @kuby's comment. React now recommends using a function with prevState instead of directly setting the state. This is because state updates may be asynchronous. So, using a function is a better approach here. If we don't use a function that does not mean always there will be problems but there could be and being in the safe side is always a better approach.

Related doc: https://reactjs.org/docs/state-and-lifecycle.html

like image 56
devserkan Avatar answered Aug 23 '26 07:08

devserkan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!