I am trying to apply best practices when changing multiple property values of a nested object in my component's state.
My component code currently looks like this:
class App extends Component {
state = {
object: {
a: 10,
b: 7,
c: 12,
}
}
render() {
return (
<div>
<button onClick={this.setState({ object: { a: 5 }})}>change value a </button>
<button onClick={this.setState({ object: { b: 2 }})}>change value b </button>
<button onClick={this.setState({ object: { c: 3 }})}>change value c </button>
</div>
<p>{this.state.object.a}</p>
<p>{this.state.object.b}</p>
<p>{this.state.object.c}</p>
);
}
}
Before any button is clicked, you see three buttons followed by paragraphs reading 10
, 7
and 12
on the page.
Once I click the first button labeled "change value a", value b
and c
are destroyed in my components state object which causes only the value of 5
to show. If I click the second button, then only 2
will show and prop a
and c
are gone.
I understand the behaviour, however I would like to know the best way to solve it. I want to keep it so all the values showing, and be able to update them in any order while the other values remain.
I am also pretty sure I am mutating the state directly and I know this is bad practice. I just don't know the right practice in this situation.