In my case, I'm using React.js and I would like to dynamically update the values in the deployOptions
object.
For example -
initial state looks like:
getInitialState() {
return {
deployOptions: {
config: null,
action: 'deploy',
env: 'qa'
}
}
}
Obviously this is not correct - but this is what I'm trying to achieve
configOptionChange(option) {
// option -> { key: 'env', value: 'prod' }
this.setState({
[deployOptions.option.key]: option.value
});
}
so that my state would then be
{
deployOptions: {
config: null,
action: 'deploy',
env: 'prod' // only this changes
}
}
To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.
Values of an object's properties can be another object. We can access nested properties of an object or nested objects using the dot notation (.) or the bracket notation []. Nested properties of an object can be accessed by chaining key or properties names in the correct sequence order.
Computed property names That allows you to put an expression in brackets [] , that will be computed and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties already.
The value of many properties is a reference to another resource. If the value of a property is a reference to a resource, the PropertyRequest might contain a NestedPropertyName object instead of the PropertyName object for the property.
It's not especially pretty, but I think this is the best you can do with ES6:
configOptionChange({ key, value }) {
this.setState({
...this.state,
deployOptions: {
...this.state.deployOptions,
[key]: value
}
});
}
It's basically equivalent to your own Object.assign
solution but using the ES6 spread (...
) operator (and argument destructuring for good measure).
Here's a second option that isn't as clever but feels a little cleaner to me:
configOptionChange({ key, value }) {
const { deployOptions: prevDeployOptions } = this.state;
const deployOptions = { ...prevDeployOptions, [key]: value };
this.setState({ ...this.state, deployOptions });
}
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