Skip to content
Advertisement

Only update one item from ReactJS state items

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>
    }
}

Advertisement

Answer

You can spread the existing state to maintain the existing values.

planHandler(plan) {
    const data = this.state.planData
    this.setState({ planData: { 
       ...data, 
       id: plan 
    }});
}
Advertisement