user10952539
user10952539

Reputation:

React setState is overwriting state

I have a form with one input field of name, and its onChange method I have this following code:

    onChangeUpdateForm(e) {
    this.setState({
        currentService: {
            [e.target.name]: e.target.value
        }
    })
};

I want to update currentService's name with the new value, but everything in state gets overwritten. How can I update one single value of an object in state?

Upvotes: 0

Views: 61

Answers (1)

wdm
wdm

Reputation: 7189

I want to update currentService's name with the new value, but everything in state gets overwritten.

Because you're replacing the entire object. Try this:

this.setState({
    currentService: {
        ...this.state.currentService,
        [e.target.name]: e.target.value
    }
});

Upvotes: 3

Related Questions