score:15

Accepted answer

ensure that component state is updated via the setstate() method, rather than via direct modification as you are currently doing.

there are a number of ways to update nested data in a complex state structure - a simple solution that should work in your case would be:

class app extends component {

    state = {
        foo: {
            title: "my title",
            bar: {}
        }
    }

    componentdidmount() {

       // create new "bar" object, cloning existing bar into new bar 
       // and updating test key with value "123"
       const newbar = { ...this.state.foo.bar, test : "123" };

       // create new "foo" object, cloning existing foo into new foo
       // and updating bar key with new bar object
       const newfoo = { ...this.state.foo, bar : newbar };

       // calling setstate() correctly updates state and triggers 
       // re-render. here we replace the existing foo with the newly
       // created foo object
       this.setstate({ foo : newfoo });

       // this.state.foo.bar = { "test": "123" };
    }
}

score:8

you could do it like this


componentdidmount() {
    let copyfoo = { ...this.state.foo}; //create a new copy
    copyfoo.bar = { "test": "123" } //change the value of bar
    this.setstate({foo: copyfoo})//write it back to state
}

or you could just do

componentdidmount() {
    let copyfoo = { ...this.state.foo, bar: { "test": "123" } }; //create a new copy and change the value of bar
    this.setstate({foo: copyfoo})//write it back to state
}



Related Query

More Query from same tag