0
0
Firebasecloud~30 mins

Real-time listeners (onSnapshot) in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Real-time Listeners with Firebase onSnapshot
📖 Scenario: You are building a simple web app that shows a live list of messages from users. The messages are stored in a Firebase Firestore database. You want the app to update instantly whenever a new message is added, without needing to refresh the page.
🎯 Goal: Build a Firebase Firestore real-time listener using onSnapshot to automatically update the list of messages whenever the database changes.
📋 What You'll Learn
Create a Firestore collection reference called messagesRef pointing to the messages collection
Create a real-time listener using onSnapshot on messagesRef
Inside the listener, update a local array messages with the current documents' data
Log the updated messages array inside the listener to verify real-time updates
💡 Why This Matters
🌍 Real World
Real-time listeners are essential for chat apps, live dashboards, and collaborative tools where data must update instantly for all users.
💼 Career
Understanding how to implement real-time data updates with Firebase is a valuable skill for frontend and full-stack developers working on interactive web applications.
Progress0 / 4 steps
1
Setup Firestore collection reference
Create a constant called messagesRef that references the Firestore collection named messages using collection(db, 'messages').
Firebase
Need a hint?

Use the collection function with db and the string 'messages' to create messagesRef.

2
Create an empty array to hold messages
Create a variable called messages and set it to an empty array [] to store the message data locally.
Firebase
Need a hint?

Declare messages as an empty array using let messages = [].

3
Add a real-time listener with onSnapshot
Use onSnapshot on messagesRef to listen for real-time updates. Inside the callback, update the messages array by mapping over snapshot.docs and extracting each document's data with doc.data().
Firebase
Need a hint?

Use onSnapshot(messagesRef, callback) and inside the callback set messages = snapshot.docs.map(doc => doc.data()).

4
Log messages inside the onSnapshot listener
Inside the onSnapshot callback, add a line to log the updated messages array using console.log(messages) to verify real-time updates.
Firebase
Need a hint?

Inside the onSnapshot callback, add console.log(messages) to see updates.