Skip to content Skip to sidebar Skip to footer

Firestore, Onsnapshot() Or Async/await Issue Or Both

I'm trying to get an array of changes using Firebase Firestore's onShapshot(). I'm having trouble retrieving data through onSnapshot(); I may be in trouble with async/await as well

Solution 1:

Have a look at this answer which explains the difference between the get() and onSnapshot() methods.

In a nutshell:

  • When you use get() you retrieve all the documents of the collection only once (like a "get and forget").
  • When you use onSnapshot() you constantly listen to the collection.

Note that onSnapshot() is not an asynchronous method, while get() is => don't call onSnapshot() with await.


Since, from your question, it seems that you want to get the list of friends by calling the getAllFriends() method, do as follows:

const getAllFriends = async (userName) => {
    const querySnapshot = await db
      .collection('user')
      .doc(userName)
      .collection('friends')
      .get();
    return querySnapshot;
  };

  let johnFriends = awaitgetAllFriends('john');
  johnFriends.forEach(doc => {
    console.log(doc.id, ' => ', doc.data());
  });

More possibilities are to be found in the Firestore doc, here and here.

Post a Comment for "Firestore, Onsnapshot() Or Async/await Issue Or Both"