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:
class Pricing extends Component {
constructor() {
super();
this.state = {
planData: {
id: 3,
price: 0,
vpnEnabled: false,
cloudEnabled: false,
cloudSpace: 0
}
};
}
planHandler(plan) {
this.setState({ planData: { id: plan }});
}
render() {
<div>
<button onClick={() => this.planHandler(2)}>Submit</button>
</div>
}
}
You can spread the existing state to maintain the existing values.
planHandler(plan) {
const data = this.state.planData
this.setState({ planData: {
...data,
id: plan
}});
}
Access planData from state using this.state.planData
You need the spread operator - ....
planHandler(plan) {
this.setState({ planData: { ...(this.state.planData), id: plan }});
}
Spread breaks open the object keys and properties. Since the above code will lead to id key twice, the one later overrides the first one.
You can use the spread operator to do so something like
planHandler(plan) {
this.setState({ planData: {...this.state.planData, id: plan }});
}
This will keep the other values intact while updating the things we need to update