I want to fetch data for every object in array passed as props (rootComments) and add the data to object properties:
useEffect(() => {
rootComments.map(rootComment => {
if (rootComment.kids) {
rootComment.kidsText = []
fetchKidsText(rootComment.kids)
}
})
console.log(rootComments)
rootComments.map(comment => console.log(Object.values(comment)))
}, [rootComments])
const fetchKidsText = async (ids) => {
await Promise.all(
ids.map(id => fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`).then(response => response.json()).then(result => {
rootComments.map(comment => {
if (comment.id === result.parent) {
comment.kidsText = comment.kidsText.concat(result.text)
}
})
}))
);
}
It seems like it doesn't work, I can't render rootComments.map(comment => comment.kidsText) and I can't log it as rootComments.map(comment => console.log(Object.values(comment))) (acts like there's no new kidsText property) or as rootComments.map(comment => console.log(comment.kidsText)) (returns empty array).
But. When I log console.log(rootComments) it returns array of objects with new kidsText property.
My first thought was that useEffect() doesn't wait for rootComments to fetch inside another component but it doesn't seem to be a problem so maybe it's something inside fetchKidsText() or with the way it interacts with useEffect()?