3

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, not quite sure...

Can you see where there are problems?

Output should be (but it is currently):

1. New friends: ... // via onSnapshot(). Should not be empty, but it is (However, it does get populated afterwards).
2. All friends: ... // Should not be empty, but it is.
3. Fred's friends: ... // Should not be empty, but it is.

Code:

const getAllFriends = async () => {
    // Gets all friends by connecting to Firestore's onSnapshot stream.

    const getNewFriends = async () => {
        // Sets up a onSnapshot() stream, and returns a newFriends array with their names.
        // Problem: It initially return an empty array, when it shouldn't be empty.

        let newFriends = [];
        await db.collection("user").doc("john").collection("friends").onSnapshot(snapshot => {
            snapshot.docChanges().forEach(change => {
                newFriends.push({ friend: "Emily" });
            });
        });

        console.log("1. New friends: ", newFriends, newFriends.length); // Length should not be 0.
        return newFriends;
    }

    // John starts with no friends:
    let friends = []; 

    // John should now have found some friends:
    let friendChanges = await getNewFriends(); 
    friends = friends.concat(friendChanges);

    console.log("2. All friends:", friends); // Should contain a few Emilys.
    return friends;
};

let johnFriends = await getAllFriends();
console.log("3. John's friends:", friends); // Should contain a few Emilys.
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
daCoda
  • 3,583
  • 5
  • 33
  • 38

2 Answers2

4

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 = await getAllFriends('john');
  johnFriends.forEach(doc => {
    console.log(doc.id, ' => ', doc.data());
  });

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

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • Thanks @Renaud, I could use get() but this will only get the data once (?); I'm wanting to set up a listener (thus want to use onSnapshot()). I think I'll have to iterate friendChanges another way... – daCoda Oct 26 '20 at 01:32
  • Can you please explain what is your exact goal? You can very well set a listener to the `collection("user").doc("john").collection("friends")`collection. But note that if you need to listen to `collection("user").doc("Emily").collection("friends")`, you'll need to set another listener. If you need to listen to ALL the friends documents, you should listen to a [Collection group query](https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query) like `db.collectionGroup('friends')`. Tell me if that is corresponding to your needs, and I'll update the answer. – Renaud Tarnec Oct 26 '20 at 12:20
  • 1
    This is what should happen: When John logs in, John gets a HTML rendered list of friends using data from `db.collection("user").doc("john").collection("friends")`. When john adds a new friend, his Firestore friends collection gets updated, and so should his HTML rendered list of friends (which is why I think `onSnapshot()` may be the way to go. I suppose I can have a `get()` initially when he logs on, and also have an `onSnapshot()` to listen to later changes; curious to know what you think, thanks!). – daCoda Oct 26 '20 at 23:58
0

I think you just want to track newly added John's friends and add them to the johnFiends array. Perhaps you can just add the onsnapshot listener on top of @Renaud's suggestion:

const getAllFriends = async (userName) => {
    const querySnapshot = await db
      .collection('user')
      .doc(userName)
      .collection('friends')
      .get();
    // You may need check for querySnapshot.empty before proceed
    let allFriends = querySnapshot.docs.map(doc => doc.data());
    return allFriends;
  };

let johnFriends = await getAllFriends('john');
console.log("All John's friends:", johnFriends);

const unsubscribe = db.collection("user").doc("john").collection("friends")
    .onSnapshot(snapshot => {
        snapshot.docChanges().forEach(change => {
            if (change.type === "added") {
                johnFriends.push(change.doc.data());
                console.log("New John's friend:", change.doc.data());
                console.log("New all John's friends:", johnFriends);
            };
        });
    });

Note that onsnapshot is mostly for real-time tracking of data change at the backend and what you should do later in the frontend, therefore you should apply it on real-time handler instead of incorporate it inside a normal data pulling function, e.g. getAllFriends(). In short, handle real-time changes separately.

Antonio Ooi
  • 1,601
  • 1
  • 18
  • 32