Simon Knight Simon Knight - 3 months ago 32
React JSX Question

reactJs update state object without overwriting the object

I am having problems updating an object in this.state. Basically I have a form with multiple range sliders. Each time the slider is changed I want to update the this.state.dreadModel object, however I only seem to be able to overwrite it.

This is what I have tried so far:

this.setState( update ( this.state.dreadModel, { dreadModel: { [name]: e.target.value } } ), function () {
console.log(this.state);
});


The error I get with the above code is "Uncaught ReferenceError: update is not defined".

I feel like I am very close, but I cant quite get the syntax quite right.

Oh, here is the code I was using that would just overwrite the object each time a sliders value was changed.

this.setState({ dreadModel: {[name]: e.target.value }}, function () {
console.log(this.state);
});

Answer

What I usually do if I need to update a nested object, is something more like:

var dreadModel = {...this.state.dreadModel, [name]: e.target.value };
//or, if no ES6:
//var dreadModel = Object.assign({}, this.state.dreadModel);
//dreadModel[name] = e.target.value;
this.setState({ dreadModel: dreadModel }, function () {
    console.log(this.state);
});