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.
Have a look at this answer which explains the difference between the get()
and onSnapshot()
methods.
In a nutshell:
get()
you retrieve all the documents of the collection only once (like a "get and forget").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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.