Reputation: 15665
In a component I have:
constructor() {
super();
this.state = {
lists: [],
items: {}
};
}
handleAddList(s) {
var temp= this.state.lists.slice(0,this.state.lists.length);
temp.push(s);
this.setState({lists: temp},function(){
var toAdd={};
toAdd[s]=[];
How do I add toAdd
to this.state.items
?
UPDATE,
I think I got it working with the following:
var ourLists = this.states.items;
ourlists[s] = [];
and then just setState.
I'm having trouble understanding the basic syntax of two lines:
toAdd[s] = []; // is this just the way you specify a key value pair where the value is an array?
Upvotes: 5
Views: 25880
Reputation: 1941
I created a simple codepen for you. In general if you want to add new value to an object in your state, you can't do both at the same time, first you need to create the key then to give it a value. (this would be the old way):
var obj = {};
obj["newKey"] = [];
obj.newKey = [<some value>]
Now you can use Object.assign()
which will help you adding a new property to an object, while keeping things in order. By order I mean:
Object.assign(
{<typically new empty object>},
{<the old object you want to change>},
{<the new field + value to add>}
)
Make sure to keep the order otherwise old value would overwrite new!!!.
After you've done that you can set the value of the new state to the new object you've created.
Upvotes: 4