Today I Learned how to get all documents in a collection in Firestore with async/await
and for...of
by using the .docs
property.
Firebase documentation has examples with .then
to get the result from a Promise.
const logCities = () => {
let citiesRef = db.collection('cities');
let allCities = citiesRef.get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
}
But it can be written easier with async/await.
const logCities = async () => {
let citiesRef = db.collection('cities');
let allCities = await citiesRef.get();
for(const doc of allCities.docs){
console.log(doc.id, '=>', doc.data());
}
}
I think this is more readable, two less lines and .docs
allows us to use for of
.
Top comments (6)
two lines:
thanks man, came in handy :)
I have some questions regarding async. i have code that looks like this:
queryRooms = async () => {
console.log('line 231');
let recentQuery = await this.chatRooms.where("uidArray", "in",
[this.user.uid+this.state.value.objectID,
this.state.value.objectID+this.user.uid]).get();
for (const qSnap of recentQuery.docs) {
console.log(qSnap.id);
let messagesRef = await this.chatRooms.doc(qSnap.id)
.collection('messages').get();
for (const messages of messagesRef.docs) {
console.log(messages.id, messages.data())
}
}
I call queryRooms in my react app everytime I change the value of the dropdownlist that has teachers students can chat with. However, my problem is that console.log('line 231') is being ran every time that I change the state but then I don't receive the requested information. After a random amount of presses I finally get a weird looking data structure from the queryRooms function. Is there a visible flaw with my async/await structure?
thanks for sharing bro
helped me a lot with some async problems I was having - and much more readable. thanks for sharing!
I am not able to console.log(snapshot) after await citiesref.get();