Set a dictionary inside a state dictionary in React

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
}



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

Tags:

Reactjs