Problem:
I am trying to modify only one item from plan data using this.setState({ planData: { id: plan }});
but by doing so, all my other items become undefined. I found a workaround by adding all other items to my setState, but it doesn’t look good at all. Is there a way to only modify a single item from planData without having to set all the other at the same time.
Sample Code:
JavaScript
x
25
25
1
class Pricing extends Component {
2
constructor() {
3
super();
4
this.state = {
5
planData: {
6
id: 3,
7
price: 0,
8
vpnEnabled: false,
9
cloudEnabled: false,
10
cloudSpace: 0
11
}
12
};
13
}
14
15
planHandler(plan) {
16
this.setState({ planData: { id: plan }});
17
}
18
19
render() {
20
<div>
21
<button onClick={() => this.planHandler(2)}>Submit</button>
22
</div>
23
}
24
}
25
Advertisement
Answer
You can spread the existing state to maintain the existing values.
JavaScript
1
8
1
planHandler(plan) {
2
const data = this.state.planData
3
this.setState({ planData: {
4
data,
5
id: plan
6
}});
7
}
8