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" };
}
}
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" };
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With