yash03agrawal
yash03agrawal

Reputation: 9

Return array of data from firestore query

I want to retrieve information of all the users who are friends of a particular user. To return a single json array I am pushing data first to an array and then returning the data but looks like data is returning empty due to asynchronous behavior of firestore queries. Can anyone please help how to return data after all values get pushed to it.

export async function getUserFriendsDetails(userId) {
    var data = {
        results: []
    }
    getUser(userId).then((snapshot) => {
        snapshot.data().friends.forEach(friend => {
            getUserDetails(friend).then((result) => {
                data.results.push(result.data()) // data is getting pushed here
            })
        })
    })
    return data;  // data is empty array here
}

Upvotes: 0

Views: 98

Answers (1)

Alekhya Satya
Alekhya Satya

Reputation: 191

We can use a callback to return once the entire data is populated.

export async function getUserFriendsDetails(userId) {
    var data = {
        results: []
    }
    getUser(userId).then((snapshot) => {
        snapshot.data().friends.forEach(friend => {
            getUserDetails(friend).then((result) => {
                data.results.push(result.data()) // data is getting pushed here
            })
        },function(data){
          alert(data);// Entire data
          })
    })
    return data;  // data is empty array here
}

Upvotes: 1

Related Questions