0

I have thoroughly gone through all the asked question and none of them apply to my problem directly. I am looping through an array of user ids and matching them to get a user from my firestore db. I get the result back with no problem but when i store it in the state array and run a console log, my state array is always empty. The first console.log works and shows the results from the db.

Here's my code:

const UsersScreen = (props) => {

    const [state, setState] = useState({
        users: []
    });  

    const getUserProfiles = () => {
        let users = [];
        //networkUsers is an array with the ids
        networkUsers.forEach(userId => { 
            db.doc(userId).get().then((doc) => {
                users.push(doc.data());
                console.log('localusers', users)
            }).catch((error) => {
                console.log('caught error', error)
            })
        });

        setState({ users: users });
    };


    useEffect(() => {
        getUserProfiles();
    }, []);

console.log('state', state.users)
}

Please help.

abdi
  • 519
  • 1
  • 5
  • 16

1 Answers1

4

The logic that fetches the document from Firestore is asynchronous. The call to setState is synchronous though. It will always before the document has been fetched. The solution would be to fetch the documents then set the state. Here is an example:

const UsersScreen = (props) => {
  const [state, setState] = useState({
    users: [],
  });

  const getUserProfiles = () => {
    Promise.all(networkUsers.map((userID) => db.doc(userId).get()))
      .then((docs) => {
        setState({ users: docs.map((doc) => doc.data()) });
      })
      .catch((err) => {
        console.log("caught error", error);
      });
  };

  useEffect(() => {
    getUserProfiles();
  }, []);

  console.log("state", state.users);
};

The Promise.all call resolves once every user has been fetched from the Firestore (maybe you could fetch them at once though). Once we have the users we loop over them with map to extract the data of the document and set the state. Here is an alternative with async/await:

const UsersScreen = (props) => {
  const [state, setState] = useState({
    users: [],
  });

  const getUserProfiles = async () => {
    try {
      const docs = await Promise.all(
        networkUsers.map((userID) => db.doc(userId).get())
      );

      setState({ users: docs.map((doc) => doc.data()) });
    } catch (err) {
      console.log("caught error", error);
    }
  };

  useEffect(() => {
    getUserProfiles();
  }, []);

  console.log("state", state.users);
};
Samuel Vaillant
  • 3,667
  • 1
  • 14
  • 21
  • This works. Can the same be done in a async await function? – abdi Apr 15 '20 at 12:02
  • 1
    @abdi Yes, you can use `for await...of` in order to use async await, but then you will need to `setState` for each iteration, so `Promise.all` would be much better https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of – zb22 Apr 15 '20 at 13:28
  • 1
    Yes async/await is possible. I've updated the example with this alternative. – Samuel Vaillant Apr 15 '20 at 14:49