Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a dictionary inside a state dictionary in React

Tags:

reactjs

I have the following React based component which has a dictionary object (foo) that contains another dictionary (bar) for it's state.

I want to set the value of the inner dictionary but can't figure out how to do it:

class App extends Component {

    state = {
        foo: {
            title: "My title",
            bar: {}
        }
    }
    componentDidMount() {
       this.state.foo.bar = { "test": "123" };
    }
}
like image 775
R OMS Avatar asked Oct 09 '19 21:10

R OMS


2 Answers

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
}


like image 117
harisu Avatar answered Sep 30 '22 03:09

harisu


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" };
    }
}
like image 30
Dacre Denny Avatar answered Sep 30 '22 01:09

Dacre Denny