0

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]);
}
1
  • You are overwriting data every time (sort of, setData is an async function so effectively only the last update will be visible). You want to make the whole children list, then set it once. You can accomplish this without mutation: setData({ children: res.data().owned.map((e, i) => ({id: i, name: e })) }) Commented Dec 2, 2021 at 7:42

2 Answers 2

1

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

@MarcShayne you should be accepting the answer that was first posted if it's a duplicate answer.
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.