小编use*_*312的帖子

useEffect doesn't wait Promise.all?

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)
        }
      })
    }))
  );
}
Run Code Online (Sandbox Code Playgroud)

It seems like it …

reactjs fetch-api

2
推荐指数
1
解决办法
146
查看次数

标签 统计

fetch-api ×1

reactjs ×1