Simon Knight Simon Knight - 1 year ago 101
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]: } } ), function () {

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]: }}, function () {

Answer Source

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

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