1

I want to retrieve data from Firestore as I map through an object to see if the user is online. I'm not sure how to retrieve the data.

When I console.log userInLobby (as shown below), I get [Promise] array.

If I try to set a variable before the firebase call, I cannot change the variable inside the .then() function

 const userInLobby = users ? (
  users.map(userdata => {
    if (userdata.status === "online") {
      var user =
        firebase.firestore().collection("users").doc(userdata.id).get().then(user => {
          return { username: user.data().username };
        })
      return user
    }
    else {
      return null;
    }
  })
) : (null);

How can I access the [Promise] or is there another way to structure this code?

1 Answer 1

2

It looks like you are trying to run an asyncronous function (firebase.firestore().collection("users").doc(userdata.id).get()) inside a map function.

That won't work. The map function will just return an array of promises.

What you need to do is use Promise.all() to get the result when all the promises return.

const userInLobby = users
  && users.map(userdata => {
      if (userdata.status === 'online') {
        return firebase
          .firestore()
          .collection('users')
          .doc(userdata.id)
          .get()
      } 
    })

Promise.all(userInLobby).then(values => console.log(values))

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

Comments

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.