I have a nested state like this:
this.state = {
fields: {
subject: '',
from: {
name: '',
},
},
};
In an onChange
function I'm handling updates to these nested values.
I'm trying to build a dynamically spread setState()
for deep nests using dot notation.
For instance, with the array: const tree = ['fields','subject']
I'm able to update the subject
state value with:
this.setState(prevState => ({
[tree[0]]: {
...prevState[tree[0]],
...(tree[2] ? {
...prevState[tree[1]],
[tree[2]]: value
}
: { [tree[1]]: value })
},
}));
Since the ternary operator is ending on { [tree[1]]: value }
But when my tree
array is: const tree = ['fields','from','name']
the state value for fields.from.name
is not changing, where it should be resolving to the first part of the ternary operator:
{
...prevState[tree[1]],
[tree[2]]: value
}
Am I missing something?