Wes
Wes

Reputation: 1945

Data collection from firebase firestore in react native returns undefined outside of promise

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

Upvotes: 0

Views: 766

Answers (1)

cccn
cccn

Reputation: 949

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));
  }

Upvotes: 3

Related Questions