Reputation: 61
constructor() {
super();
this.state = {
lists: [], // this holds the name of each list
items: {} // this property names of this object are the names of the lists; their values are arrays of the items in each list
};
}
handleAddList(s) {
var curState = this.state.items;
this.setState(prevState => ({
lists: [...prevState.lists, s],
items: //I am having trouble figuring out how I can use "s" and set that as a new property of this items object.
}))
}
I want items
to get a new property whose name is from s
and whose value is, initially, []
.
Upvotes: 3
Views: 81
Reputation: 1074335
You do the same thing you did with lists
: You make a new object with all of the old properties, along with the change. Since you've said (in a comment) that you want {dog: []}
where dog
is the value of s
, you'd do it like this:
this.setState(prevState => ({
lists: [...prevState.lists, s],
items: {...prevState.items, [s]: []}
}))
The items
part of that is a combination of two things:
...
is spread properties. It's conceptually the same as array spread (what you're using with lists
) but it's new: The proposal is currently at Stage 3 but will be at Stage 4 quite soon. It's been transpiled by Babel for well over a year, and is natively supported by V8 in Chrome and SpiderMonkey in Firefox (not behind any flag).[s]
is a computed property name. It creates a property whose name is the value of s
.Upvotes: 1