0

This method is supposed to return a list of users but returning an empty array. When I console log inside the forEach loop, it prints the data but not outside of it.

  get getAllUsers() {
    const usersList = [];
    firebase
      .firestore()
      .collection('users')
      .get()
      .then(snapshot => {
        snapshot.forEach(user => {
          usersList.push(user.data());
          console.log(user.data());
        });
      });
    return usersList; // Array [] or undefined when indexed
  }

On Home.js, I call it here.

  componentDidMount() {
    const list = fireStoreDB.getAllUsers;
    console.log(list);
  }

Array [] is the console log of the method and the objects are the console log from the forEach loop.

enter image description here

1 Answer 1

3

You got an empty array, because your function is synchronous and firebase returns a promise which is asynchronous. So that's why in most cases you will get an empty array first, and after that response from firebase.

Try this one:

 async getAllUsers() {
   const usersList = await firebase
      .firestore()
      .collection('users')
      .get()
      .then(snapshot => {
        return snapshot.map(user => user.data(););
      });
    return usersList;
  }

And then in Home.js

componentDidMount() {
    fireStoreDB.getAllUsers().then(list => console.log(list));
  }
Sign up to request clarification or add additional context in comments.

2 Comments

I get syntax error with the async on the get function. I tried this which won't work either: getAllUsers = async () => { const usersList = await firebase .firestore() .collection('users') .get() .then(snapshot => { return snapshot.map(user => user.data()); }); return usersList; // Array [] or undefined when indexed };
You're missing docs on snapshot return snapshot.docs.map(user => user.data()); but other than that, thanks for the solution.

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.