0

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
}

1 Answer 1

1

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
}

Sign up to request clarification or add additional context in comments.

3 Comments

still it is returning an empty array.
Write the return statement in the place of alert() statement.
Thanks but I tried returning data from there only(where alert is written) but still it is returning null. are there any other options I can try?

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.