How to Use Real Time Listener in Firestore
Use
onSnapshot() on a Firestore document or collection reference to listen for real-time updates. This method runs a callback every time the data changes, giving you live data without manual refresh.Syntax
The onSnapshot() method attaches a real-time listener to a Firestore document or collection. It takes a callback function that receives a snapshot of the data whenever it changes.
docRef.onSnapshot(callback): Listens to a single document.collectionRef.onSnapshot(callback): Listens to all documents in a collection.- The
callbackreceives a snapshot object with the current data.
javascript
const unsubscribe = docRef.onSnapshot(snapshot => { console.log('Current data:', snapshot.data()); });
Example
This example shows how to listen to real-time updates on a Firestore document called users/user123. It prints the user's data every time it changes.
javascript
import { initializeApp } from 'firebase/app'; import { getFirestore, doc, onSnapshot } from 'firebase/firestore'; const firebaseConfig = { apiKey: 'YOUR_API_KEY', authDomain: 'YOUR_AUTH_DOMAIN', projectId: 'YOUR_PROJECT_ID' }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); const userDoc = doc(db, 'users', 'user123'); const unsubscribe = onSnapshot(userDoc, (docSnapshot) => { if (docSnapshot.exists()) { console.log('User data:', docSnapshot.data()); } else { console.log('No such document!'); } }); // To stop listening later, call unsubscribe();
Output
User data: { name: 'Alice', age: 30 } // printed whenever data changes
Common Pitfalls
- Not unsubscribing the listener causes memory leaks and unnecessary reads. Always call the unsubscribe function when done.
- Using
onSnapshoton large collections without filters can cause high costs and slow performance. - Not handling the case when the document does not exist can cause errors.
javascript
/* Wrong: Not unsubscribing listener */ const unsubscribe = onSnapshot(docRef, snapshot => { console.log(snapshot.data()); }); // Listener stays active forever /* Right: Unsubscribe when no longer needed */ unsubscribe();
Quick Reference
| Method | Description |
|---|---|
| onSnapshot(ref, callback) | Attach real-time listener to document or collection |
| unsubscribe() | Stop listening to updates |
| snapshot.data() | Get current data from snapshot |
| snapshot.exists() | Check if document exists |
Key Takeaways
Use onSnapshot() to get real-time updates from Firestore documents or collections.
Always unsubscribe listeners when they are no longer needed to save resources.
Handle cases where documents might not exist to avoid errors.
Avoid listening to large collections without filters to reduce costs and improve performance.