Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  0] [ 2]  / answers: 1 / hits: 20947  / 7 Years ago, fri, december 1, 2017, 12:00:00

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?


ahh, I got it.


More From » reactjs

 Answers
15

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.


[#55787] Tuesday, November 28, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckaylab

Total Points: 311
Total Questions: 120
Total Answers: 93

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
;