3
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.

1
  • Actually, your last code should work. But, you don't need ...this.state here since React merges other parts of your state with your new qs. Commented Apr 18, 2018 at 12:31

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

this.setState(prevState => { return { qs: {...prevState.qs, catName: 'name'} } })
I tried both solutions. It's not updating the state. @devserkan And Also checked without nested state(like this.state = {catName: ''}) for this also setState not working for me. FYI, I am importing react-redux in this component.
Can you show us your whole component or upload it somewhere else like codesandbox.io or stackblitz.com?
I uploaded my code here codesandbox.io/s/github/arsarvahventures/build src->components->containers -> catalog-container @devserkan
It seems working, I can see catName is changing from "" to "name".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.