user3378165
user3378165

Reputation: 6896

Set state of object property

I have this factory method that creates functions for each change handler:

makeHandleChange = changedProperty => newVal => {
    const newState = { ...this.state, [changedProperty]: newVal };
    this.setState({ ...newState });
  };

It is being executed for example like that:

onChange={this.makeHandleChange('phoneNumber')}

How can I set the state of a property object using this function?

For example I have to setState the info.phoneNumber property:

state = {
    info: {
       phoneNumber: '',
    },
}

How can I do that with this makeHandleChange function?

Upvotes: 1

Views: 119

Answers (2)

Claire Lin
Claire Lin

Reputation: 2382

There are two ways to get this to work. One is to update your factory code so that it takes into consideration of nested state properties. The other, and probably the easier way is to pass in the entire nested object when you need to update the state.

For example, if you have a input field that updates the phoneNumber property nested in this.state.info:

    <input
      type="text"
      onChange={e => this.makeHandleChange("info")({ ...this.state.info, phoneNumber: e.target.value})}
      value={this.state.phoneNumber}
    />

In the object you pass in to the function, make sure you destruct this.state.info (i.e. ...this.state.info) before setting the new value so that none of the other nested properties gets overwritten/removed.

Upvotes: 1

Treycos
Treycos

Reputation: 7492

You could do the following by destructing your previous info state property :

makeHandleChange = changedProperty => newVal => {
    this.setState(prev => ({ info: { ...prev.info, [changedProperty]: newVal } }));
};

This solution uses the callback version of setState.

It does the equivalent of the following code:

makeHandleChange = changedProperty => newVal => {
    const { info } = this.state
    this.setState({ info: { ...info, [changedProperty]: newVal }});
};

Upvotes: 0

Related Questions