Debojit Kaushik
Debojit Kaushik

Reputation: 103

How do we partially update a state in react?

I was wondering what is the best way to partially update a state of a component in React/React-Native. Other than the fact that I can make a function which takes the current state and creates a new state and merges the new {key:value} and the previous state. For example:

{
      dataStream:[//having data here], 
      formData: {
         'first_name': 'Richard',
         'last_name' : 'Barbieri',
      } 
}

I want to update last_name to another value. When I call this.setState(formData:{{'last_name':newValue}}), it resets the formData dictionary to just last name: new Value. Is there a way to this efficiently?

Upvotes: 7

Views: 14981

Answers (2)

A. L
A. L

Reputation: 12649

I think there are two things you could try:

  1. Spread operator

liks so

this.setState({
    formData: {
        ...this.state.formData, 
        "last_name" : newValue 
    } 
});

or

  1. Take current state's first_name and reapply it:

like so

this.setState({ 
    formData: { 
        "first_name": this.state.formData.first_name, 
        "last_name" : newValue 
    } 
})

I'm not too sure about the first one, but I think the second one should work.

Upvotes: 13

Ji aSH
Ji aSH

Reputation: 3457

What happens is normal because you reassign the whole forData.

If you want to add something to the existing form data do something like that (there are plenty of other solutions ^^)

this.setState({
    formData: Object.assign(this.state.formData, { 'last_name': newValue } 
})

Upvotes: 4

Related Questions