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:
JavaScript
x
10
10
1
getInitialState() {
2
return {
3
deployOptions: {
4
config: null,
5
action: 'deploy',
6
env: 'qa'
7
}
8
}
9
}
10
Obviously this is not correct – but this is what I’m trying to achieve
JavaScript
1
9
1
configOptionChange(option) {
2
3
// option -> { key: 'env', value: 'prod' }
4
5
this.setState({
6
[deployOptions.option.key]: option.value
7
});
8
}
9
so that my state would then be
JavaScript
1
8
1
{
2
deployOptions: {
3
config: null,
4
action: 'deploy',
5
env: 'prod' // only this changes
6
}
7
}
8
Advertisement
Answer
It’s not especially pretty, but I think this is the best you can do with ES6:
JavaScript
1
10
10
1
configOptionChange({ key, value }) {
2
this.setState({
3
this.state,
4
deployOptions: {
5
this.state.deployOptions,
6
[key]: value
7
}
8
});
9
}
10
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:
JavaScript
1
6
1
configOptionChange({ key, value }) {
2
const { deployOptions: prevDeployOptions } = this.state;
3
const deployOptions = { prevDeployOptions, [key]: value };
4
this.setState({ this.state, deployOptions });
5
}
6