How to Use Real Time Listener in Firestore
Use Firestore's
onSnapshot() method to set up a real time listener that automatically updates your app when data changes. Attach onSnapshot() to a document or collection reference to receive live updates without manual refresh.Syntax
The onSnapshot() method listens for real-time updates on a Firestore document or collection. It takes a callback function that runs every time the data changes.
docRef.onSnapshot(callback): Listens to a single document.collectionRef.onSnapshot(callback): Listens to a collection of documents.- 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. It prints the document data whenever 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 docRef = doc(db, 'users', 'user123'); const unsubscribe = onSnapshot(docRef, (docSnap) => { if (docSnap.exists()) { console.log('User data:', docSnap.data()); } else { console.log('No such document!'); } }); // To stop listening later, call unsubscribe();
Output
User data: { name: 'Alice', age: 30 }
Common Pitfalls
- Not unsubscribing the listener can cause memory leaks; always call the returned
unsubscribe()when done. - Using
onSnapshot()on large collections without filters can cause performance issues. - Not handling the case when the document does not exist leads to errors; always check
snapshot.exists().
javascript
/* Wrong: Not unsubscribing listener */ const unsubscribe = onSnapshot(docRef, (docSnap) => { console.log(docSnap.data()); }); // Listener runs forever, causing memory leaks /* Right: Unsubscribe when no longer needed */ // Call unsubscribe() to stop listening unsubscribe();
Quick Reference
| Method | Description |
|---|---|
| onSnapshot(docRef, callback) | Listen to real-time updates on a single document |
| onSnapshot(collectionRef, callback) | Listen to real-time updates on a collection |
| unsubscribe() | Stop listening to updates to avoid memory leaks |
| snapshot.exists() | Check if the document exists before accessing data |
| snapshot.data() | Get the current data from the snapshot |
Key Takeaways
Use onSnapshot() to get real-time updates from Firestore documents or collections.
Always unsubscribe listeners when they are no longer needed to prevent memory leaks.
Check if the document exists before accessing data to avoid errors.
Avoid listening to large collections without filters to maintain good performance.
The callback receives a snapshot object with the latest data on every change.