aclspy
aclspy

Reputation: 61

How do I add a new property to an empty object that is stored in a component's state?

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

Answers (1)

T.J. Crowder
T.J. Crowder

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:

  1. The ... 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).
  2. The [s] is a computed property name. It creates a property whose name is the value of s.

Upvotes: 1

Related Questions