M
M
myskypesla2018-10-22 14:47:54
React
myskypesla, 2018-10-22 14:47:54

How to replace object property inside state object?

There is a component inside it:
this.state = {
sms: {
code: null,
startTime: 60,
disabled: false,
},
};
I need to change only the disabled value inside the sms
object . I do this:
someFunction = () => {
this.setState({...this.state.sms, disabled: true});
}
And there is a complete rewriting of the sms object
Question: how to change only the disabled value?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Matrosov, 2018-10-22
@myskypesla

It is necessary to rewrite the sms object

someFunction = () => {
      const {sms} = this.state;
      sms.disabled = true;
      this.setState({sms});
}

This way you will update the disabled field in sms
--------
Or else like this
someFunction = () => {
      this.setState({sms: {...this.state.sms, disabled: true}});
}

--------
still possible
someFunction = () => {
      this.setState(prevState=>({sms: {...prevState.sms, disabled: true}}));
}

The last option is the most resistant to collisions associated with state changes elsewhere in the program.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question