Bird
Raised Fist0
Firebasecloud~20 mins

Real-time listeners (onSnapshot) in Firebase - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Real-time Listener Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ service_behavior
intermediate
2:00remaining
Understanding onSnapshot real-time updates

What happens when you attach an onSnapshot listener to a Firestore document?

Choose the correct behavior of the listener.

Firebase
const unsub = docRef.onSnapshot(doc => {
  console.log(doc.data());
});
AThe listener fetches the document once and then stops listening.
BThe listener triggers only if the document does not exist.
CThe listener only triggers when the document is deleted.
DThe listener fetches the document initially and then listens for real-time updates, triggering the callback on every change.
Attempts:
2 left
💡 Hint

Think about what 'real-time' means in Firestore listeners.

❓ Configuration
intermediate
2:00remaining
Properly detaching an onSnapshot listener

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.

Firebase
const unsubscribe = docRef.onSnapshot(snapshot => {
  console.log(snapshot.data());
});
ACall <code>docRef.offSnapshot()</code> to stop listening.
BSet <code>unsubscribe = null</code> to stop listening.
CCall <code>unsubscribe()</code> when you want to stop listening.
DListeners stop automatically after 5 minutes; no action needed.
Attempts:
2 left
💡 Hint

Remember the function returned by onSnapshot.

❓ Architecture
advanced
3:00remaining
Designing efficient real-time updates for a chat app

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?

AFetch all messages once with <code>get()</code> and poll every 10 seconds for new messages.
BAttach an <code>onSnapshot</code> listener to a query that fetches only the latest 50 messages ordered by timestamp.
CAttach an <code>onSnapshot</code> listener to the entire <code>messages</code> collection and filter messages client-side.
DAttach multiple <code>onSnapshot</code> listeners to each message document individually.
Attempts:
2 left
💡 Hint

Think about limiting data and using queries.

❓ security
advanced
3:00remaining
Security rules impact on onSnapshot listeners

You have an onSnapshot listener on a Firestore collection. If a user does not have read permission for some documents, what will happen?

AThe listener will only receive documents the user has permission to read; others are filtered out.
BThe listener will receive all documents regardless of permissions.
CThe listener will fail with a permission error and stop listening.
DThe listener will receive documents but with empty data for unauthorized ones.
Attempts:
2 left
💡 Hint

Consider how Firestore security rules filter data.

🧠 Conceptual
expert
3:00remaining
Behavior of onSnapshot with offline persistence enabled

When Firestore offline persistence is enabled, what is the behavior of an onSnapshot listener when the device is offline?

AThe listener immediately triggers with cached data and waits for online updates.
BThe listener does not trigger until the device is back online.
CThe listener triggers only once and then stops.
DThe listener triggers with empty data and errors out.
Attempts:
2 left
💡 Hint

Think about offline support and cached data.

Practice

(1/5)
1. What does the onSnapshot method do in Firebase Firestore?
easy
A. It creates a new Firestore database.
B. It deletes a document from Firestore.
C. It uploads files to Firebase Storage.
D. It listens for real-time updates to data and runs a callback when data changes.

Solution

  1. Step 1: Understand the purpose of onSnapshot

    The onSnapshot method is designed to listen for changes in Firestore data in real-time.
  2. Step 2: Identify what happens when data changes

    When data changes, onSnapshot runs a callback function to update the app immediately.
  3. Final Answer:

    It listens for real-time updates to data and runs a callback when data changes. -> Option D
  4. Quick Check:

    onSnapshot = real-time updates listener [OK]
Hint: Remember: onSnapshot = live updates listener [OK]
Common Mistakes:
  • Confusing onSnapshot with data deletion
  • Thinking onSnapshot uploads files
  • Assuming onSnapshot creates databases
2. Which of the following is the correct syntax to start listening to a Firestore collection named users using onSnapshot?
easy
A. db.users.onSnapshot(snapshot => { /* handle data */ });
B. db.collection('users').getSnapshot(snapshot => { /* handle data */ });
C. db.collection('users').onSnapshot(snapshot => { /* handle data */ });
D. db.collection('users').listen(snapshot => { /* handle data */ });

Solution

  1. Step 1: Recall Firestore collection access syntax

    Firestore collections are accessed with db.collection('collectionName').
  2. Step 2: Confirm the correct method for real-time listening

    The method to listen for real-time updates is onSnapshot, not getSnapshot or listen.
  3. Final Answer:

    db.collection('users').onSnapshot(snapshot => { /* handle data */ }); -> Option C
  4. Quick Check:

    Correct syntax = collection + onSnapshot [OK]
Hint: Use collection('name').onSnapshot for real-time data [OK]
Common Mistakes:
  • Using .users instead of .collection('users')
  • Using getSnapshot or listen instead of onSnapshot
  • Missing parentheses or arrow function syntax
3. Given the code below, what will be logged if the users collection has two documents with names 'Alice' and 'Bob'?
db.collection('users').onSnapshot(snapshot => {
  snapshot.forEach(doc => {
    console.log(doc.data().name);
  });
});
medium
A. Alice\nBob
B. undefined\nundefined
C. Error: doc.data is not a function
D. No output

Solution

  1. Step 1: Understand onSnapshot callback behavior

    The callback receives a snapshot of the collection documents at the time of the update.
  2. Step 2: Loop through each document and access data

    Using snapshot.forEach, each document's data is accessed with doc.data(), and the name field is logged.
  3. Final Answer:

    Alice\nBob -> Option A
  4. Quick Check:

    doc.data().name logs names correctly [OK]
Hint: Use doc.data() inside forEach to get document fields [OK]
Common Mistakes:
  • Trying to access doc.name instead of doc.data().name
  • Using snapshot.docs without forEach
  • Expecting synchronous return instead of callback
4. What is wrong with this code snippet that uses onSnapshot?
const unsubscribe = db.collection('messages').onSnapshot(snapshot => {
  snapshot.forEach(doc => {
    console.log(doc.data().text);
  });
});
// Later in code
unsubscribe();
unsubscribe();
medium
A. Not unsubscribing causes memory leaks.
B. The code is correct and unsubscribing twice is safe.
C. Calling unsubscribe twice causes an error.
D. onSnapshot does not return an unsubscribe function.

Solution

  1. Step 1: Understand unsubscribe function from onSnapshot

    The onSnapshot method returns a function to stop listening when called.
  2. Step 2: Analyze calling unsubscribe multiple times

    The unsubscribe function is idempotent; calling it more than once is safe and has no effect after the first call.
  3. Final Answer:

    The code is correct and unsubscribing twice is safe. -> Option B
  4. Quick Check:

    Unsubscribe function safe to call multiple times [OK]
Hint: Unsubscribe() is safe to call multiple times [OK]
Common Mistakes:
  • Forgetting to unsubscribe (memory leaks)
  • Assuming onSnapshot does not return unsubscribe
  • Confusing unsubscribe with data operations
5. You want to listen to a Firestore document settings/config and update your app UI only when the field theme changes. How can you efficiently use onSnapshot to achieve this?
hard
A. Use onSnapshot on the document and inside callback compare previous and current theme values before updating UI.
B. Use onSnapshot on the whole collection settings and update UI on any change.
C. Call get() repeatedly every second to check for changes.
D. Use onSnapshot on the document but update UI without checking field changes.

Solution

  1. Step 1: Use onSnapshot on the specific document

    Listening to the exact document settings/config avoids unnecessary updates from other documents.
  2. Step 2: Compare previous and current theme values inside callback

    By storing the previous theme value, you can check if it changed before updating the UI, improving efficiency.
  3. Final Answer:

    Use onSnapshot on the document and inside callback compare previous and current theme values before updating UI. -> Option A
  4. Quick Check:

    Compare field changes inside onSnapshot callback [OK]
Hint: Compare old and new data inside onSnapshot callback [OK]
Common Mistakes:
  • Listening to whole collection causing extra updates
  • Polling with get() instead of real-time listener
  • Updating UI without checking if field changed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard