MarcShayne
MarcShayne

Reputation: 87

React js adding array in a useState object property

I'm pretty new to this, how do I add all of my array in the children property? You can kind of guess what I'm trying to do here, but this only gets the last array, not adding every time it loops.

for (let i = 0; i < res.data().productioncompaniesowned.length; i++) {
  setData({
    id: "root",
    name: "Production Company Owned",
    children: [{ id: i, name: res.data().productioncompaniesowned[i] }]
  });
  console.log(i);
  console.log(userData.Productioncompany[i]);
}

Upvotes: 0

Views: 76

Answers (2)

Nhut Pham
Nhut Pham

Reputation: 185

let arr = []; 
for (let i = 0; i < res.data().productioncompaniesowned.length; i++) { 
    arr.push({ 
        id: i, 
        name: res.data().productioncompaniesowned[i]
    });
};
setData({
    id: "root",
    name: "Production Company Owned",
    children: arr,
});

When u loop, one time, u add one item to state, u not push to arr, Y should have array outside and loop and then add to array. Then,setState() with this data.

Upvotes: 0

Stoobish
Stoobish

Reputation: 1362

Set a separate array for children that adds your object, like so:

var children = [];
for (let i = 0; i < res.data().productioncompaniesowned.length; i++) {
  children.push({ id: i, name: res.data().productioncompaniesowned[i] })
}
setData({
   id: "root",
   name: "Production Company Owned",
   children: children;
});

Upvotes: 1

Related Questions