1

I have the following code:

this.state = { 
    user: null
}

If the user has a name property how would I set it knowing that this.setState({user.name: 'Bob') won't work.

5 Answers 5

0
this.setState({ user: {...this.state.user, name: 'Bob'} });
Sign up to request clarification or add additional context in comments.

1 Comment

if user has other properties along with name, will be delete all what you suggest.
0
const copy = {...this.state.user}
copy.name = 'Bob'
this.setState({ user: copy })

and if you don't want to override existing properties like say age do this

const copy = {...this.state.user}
copy.name = 'Bob'
this.setState({ user: { ...user, name: copy } })

Comments

0

user itself is probably an object so you can set the state of user to an object

this.setState({ user: { name: "bob" }})

or

this.state = { 
user: {
    name: "bob"
    }
}

Comments

0

If your state contains an object, then you can update the value of nested state using the javascript spread operator. Other user parameters will not be affected.

this.setState({
...this.state,
  user: {
   ...this.state.user,
   name:'Bob'
  }
})

Comments

0

You can use spread operator for this like:

this.setState(prevState => ({
    user: { ...prevState.user, name: 'Bob' }
}))

For more info:

Comments

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.