Home > Software design >  In getServerSideProps, how to execute the return statement after all fetching is complete?
In getServerSideProps, how to execute the return statement after all fetching is complete?

Time:07-07

I have access to the username of a person and I can access their corresponding data object using one fetch from firebase. This data object has a lot of properties, including one which is called "uploads" which is an array of documentIDs where each id is that of a post uploaded by the user. I want to fetch all these documents, make it an array and return the ENTIRE array back to the page.

I have written this code so far: https://i.stack.imgur.com/OC74t.png

What is happening is that the return on line 54 executes before all elements of postIDs is looped through because of which, an empty array is returned back to the component.

Let me know if further details are required. Please help me out. Thanks in advance!

CodePudding user response:

Try to change your loop to a for...of:

for (const postID of currentUserData.uploads) {
    const postReference = doc(db, `posts/${postID}`)
    const snapshot = await getDoc(postReference)
    const postData = snapshot.data()
    postData.time = postData.time.toJSON()
    uploadsArray.push(postData)
}

return { props: { uploadsArray }}

CodePudding user response:

What about try to use Promise.all?

var promises = [];
promises.push();

// Wait for all promises to resolve
Promise.all(promises).then(function(res) { 
    // Do something...
});
  • Related