What happens when you attach an onSnapshot listener to a Firestore document?
Choose the correct behavior of the listener.
const unsub = docRef.onSnapshot(doc => {
console.log(doc.data());
});Think about what 'real-time' means in Firestore listeners.
The onSnapshot listener first fetches the current document data and then listens for any changes. It triggers the callback every time the document updates, providing real-time updates.
Given the following code, what is the correct way to stop listening to real-time updates?
const unsubscribe = docRef.onSnapshot(snapshot => {
console.log(snapshot.data());
});Choose the correct way to detach the listener.
const unsubscribe = docRef.onSnapshot(snapshot => {
console.log(snapshot.data());
});Remember the function returned by onSnapshot.
The onSnapshot method returns a function that, when called, detaches the listener. Calling unsubscribe() stops the real-time updates.
You are building a chat app using Firestore. You want to listen to new messages in a chat room in real-time but avoid unnecessary data usage and costs.
Which approach is best to achieve this?
Think about limiting data and using queries.
Listening to a query that limits results (e.g., latest 50 messages) reduces data transfer and costs. It also keeps updates efficient by only sending relevant changes.
You have an onSnapshot listener on a Firestore collection. If a user does not have read permission for some documents, what will happen?
Consider how Firestore security rules filter data.
Firestore security rules filter data before sending it to the client. The listener only receives documents the user is allowed to read. Unauthorized documents are not sent at all.
When Firestore offline persistence is enabled, what is the behavior of an onSnapshot listener when the device is offline?
Think about offline support and cached data.
With offline persistence, Firestore caches data locally. The onSnapshot listener triggers immediately with cached data, allowing the app to work offline, then updates when online.