0
0
Firebasecloud~5 mins

Real-time listeners (onSnapshot) in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you want your app to update instantly as data changes in the cloud, real-time listeners help by watching the data and sending updates right away. This avoids the need to refresh or ask for data repeatedly.
When you want a chat app to show new messages immediately as they arrive.
When you want a dashboard to update live with the latest sales numbers.
When you want a multiplayer game to sync player moves instantly.
When you want to show live comments or reactions on a post without refreshing.
When you want to keep a list of online users updated in real time.
Commands
Log in to your Firebase account to access your projects and use Firebase CLI commands.
Terminal
firebase login
Expected OutputExpected
āœ” Success! Logged in as your-email@example.com
Initialize Firestore in your project to set up the database for real-time data storage and listeners.
Terminal
firebase init firestore
Expected OutputExpected
Firestore rules and indexes files have been created. āœ” Firestore initialization complete.
Start Node.js REPL to run JavaScript code that sets up a real-time listener using onSnapshot.
Terminal
node
Expected OutputExpected
>
This JavaScript code connects to Firestore, points to a document, and sets up a real-time listener that prints data whenever it changes.
Terminal
const { initializeApp } = require('firebase/app'); const { getFirestore, doc, onSnapshot } = require('firebase/firestore'); const firebaseConfig = { apiKey: 'AIzaSyExample', authDomain: 'example.firebaseapp.com', projectId: 'example-project' }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); const docRef = doc(db, 'cities', 'SF'); const unsubscribe = onSnapshot(docRef, (doc) => { console.log('Current data:', doc.data()); });
Expected OutputExpected
Current data: { name: 'San Francisco', state: 'CA', country: 'USA' }
Stop the real-time listener when you no longer want to receive updates to save resources.
Terminal
unsubscribe()
Expected OutputExpected
No output (command runs silently)
Key Concept

If you remember nothing else from this pattern, remember: onSnapshot lets your app watch data live and react instantly to changes without asking repeatedly.

Common Mistakes
Not calling the unsubscribe function to stop the listener when it's no longer needed.
This causes unnecessary data usage and can slow down your app because it keeps listening forever.
Always save the unsubscribe function returned by onSnapshot and call it when you want to stop listening.
Using onSnapshot on a query or document reference that does not exist or is misspelled.
The listener will not receive updates and may cause errors or empty data.
Double-check your document or collection paths to ensure they exist and are spelled correctly.
Trying to use onSnapshot without initializing Firebase app and Firestore properly.
The listener will fail because it cannot connect to the database.
Always initialize Firebase app with correct config and get Firestore instance before using onSnapshot.
Summary
Use firebase login and firebase init firestore to set up your Firebase project and Firestore database.
Write JavaScript code to initialize Firebase app and Firestore, then use onSnapshot to listen to document changes in real time.
Call the unsubscribe function to stop listening when updates are no longer needed.