0 votes
in Google Cloud by
Can you provide an example of using Firestore’s onSnapshot listener in a real-world application?

1 Answer

0 votes
by

Firestore’s onSnapshot listener is used for real-time updates in applications. Consider a chat application where users need to see new messages instantly.

In JavaScript, we can use the onSnapshot method on a document reference:

let docRef = db.collection('chats').doc('room1');
let observer = docRef.onSnapshot(docSnapshot => {
console.log(`Received doc snapshot: ${docSnapshot}`);
}, err => {
console.log(`Encountered error: ${err}`);
});

Here, ‘db’ refers to Firestore database instance, ‘chats’ is the collection of all chats and ‘room1’ is a specific chat room. Whenever there’s a change in ‘room1’, onSnapshot triggers and logs the updated document snapshot.

...