Bird
Raised Fist0
Firebasecloud~20 mins

Auth state observer in Firebase - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Firebase Auth Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ service_behavior
intermediate
2:00remaining
What happens when Firebase auth state changes?

Consider the Firebase auth state observer below. What will be logged when a user signs out?

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    console.log('User signed in:', user.uid);
  } else {
    console.log('No user signed in');
  }
});
Firebase
firebase.auth().onAuthStateChanged(user => {
  if (user) {
    console.log('User signed in:', user.uid);
  } else {
    console.log('No user signed in');
  }
});
ALogs 'No user signed in'
BLogs 'User signed in:' followed by the user ID
CThrows an error because user is undefined
DDoes nothing, no logs appear
Attempts:
2 left
💡 Hint

Think about what the observer receives when the user signs out.

❓ Configuration
intermediate
2:00remaining
Which code correctly unsubscribes from Firebase auth state observer?

You want to stop listening to auth state changes to avoid memory leaks. Which option correctly unsubscribes the observer?

Firebase
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
  console.log(user ? 'Signed in' : 'Signed out');
});

// How to unsubscribe?
Afirebase.auth().removeListener('onAuthStateChanged', unsubscribe);
Bfirebase.auth().offAuthStateChanged(unsubscribe);
Cfirebase.auth().onAuthStateChanged(null);
Dunsubscribe();
Attempts:
2 left
💡 Hint

Check the return value of onAuthStateChanged.

❓ Architecture
advanced
2:00remaining
Best architecture to handle auth state in a single-page app

You build a single-page app using Firebase auth. Which architecture best ensures UI updates correctly on auth state changes?

ACall <code>onAuthStateChanged</code> inside every component that needs user info
BCall <code>onAuthStateChanged</code> once at app start and update global state accordingly
CUse <code>getCurrentUser()</code> repeatedly on user actions instead of observer
DReload the page on every auth state change to refresh UI
Attempts:
2 left
💡 Hint

Think about performance and consistency of user state.

❓ security
advanced
2:00remaining
What security risk arises if auth state observer is not used properly?

If your app does not listen to auth state changes and relies only on initial user info, what risk occurs?

AUser credentials get exposed in console logs
BFirebase throws an authentication error immediately
CUser might access protected content after signing out until page reload
DApp crashes due to missing user object
Attempts:
2 left
💡 Hint

Consider what happens if UI does not update after sign out.

🧠 Conceptual
expert
2:00remaining
Why does Firebase auth state observer trigger twice on page load?

When your app loads, the onAuthStateChanged observer fires twice: once with null and then with the user object. Why?

AFirebase first emits a default null state before confirming user session asynchronously
BIt is a bug in Firebase SDK causing duplicate events
CThe observer is registered twice accidentally in code
DBrowser caches cause the observer to fire twice
Attempts:
2 left
💡 Hint

Think about how Firebase loads user session data.

Practice

(1/5)
1. What is the main purpose of an auth state observer in Firebase?
easy
A. To store user data permanently in the database
B. To watch for user sign-in or sign-out events and respond accordingly
C. To send emails to users automatically
D. To create new user accounts without user input

Solution

  1. Step 1: Understand the role of auth state observer

    An auth state observer listens for changes in user authentication status, such as sign-in or sign-out.
  2. Step 2: Identify the correct purpose

    It helps the app respond instantly to these changes by updating the UI or user info.
  3. Final Answer:

    To watch for user sign-in or sign-out events and respond accordingly -> Option B
  4. Quick Check:

    Auth state observer = watch sign-in/out [OK]
Hint: Auth observer tracks sign-in/out changes instantly [OK]
Common Mistakes:
  • Thinking it stores user data permanently
  • Confusing it with email sending service
  • Assuming it creates accounts automatically
2. Which of the following is the correct syntax to add an auth state observer in Firebase JavaScript SDK?
easy
A. firebase.auth().onAuthStateChanged(user => { /* code */ });
B. firebase.auth().addUserObserver(user => { /* code */ });
C. firebase.auth().watchUserState(user => { /* code */ });
D. firebase.auth().observeAuth(user => { /* code */ });

Solution

  1. Step 1: Recall Firebase auth observer method

    The correct method to listen for auth state changes is onAuthStateChanged.
  2. Step 2: Match the syntax

    firebase.auth().onAuthStateChanged(user => { /* code */ }); uses the exact method name and callback syntax as per Firebase docs.
  3. Final Answer:

    firebase.auth().onAuthStateChanged(user => { /* code */ }); -> Option A
  4. Quick Check:

    Correct method = onAuthStateChanged [OK]
Hint: Look for onAuthStateChanged method name [OK]
Common Mistakes:
  • Using non-existent methods like addUserObserver
  • Mixing method names with watchUserState
  • Using observeAuth which is invalid
3. Given this code snippet, what will be logged if a user is signed in?
firebase.auth().onAuthStateChanged(user => {
  if (user) {
    console.log('User ID:', user.uid);
  } else {
    console.log('No user signed in');
  }
});
medium
A. Nothing will be logged
B. No user signed in
C. An error message about missing user
D. User ID: followed by the user's unique ID

Solution

  1. Step 1: Understand the callback behavior

    The callback runs whenever auth state changes. If a user is signed in, the user object is not null.
  2. Step 2: Check the if condition

    Since user exists, it logs 'User ID:' plus the user's unique ID (user.uid).
  3. Final Answer:

    User ID: followed by the user's unique ID -> Option D
  4. Quick Check:

    Signed-in user logs ID [OK]
Hint: If user exists, logs user.uid [OK]
Common Mistakes:
  • Assuming it logs 'No user signed in' when user is present
  • Expecting an error message incorrectly
  • Thinking nothing logs without explicit call
4. Identify the error in this Firebase auth state observer code:
firebase.auth().onAuthStateChanged(user => {
  if (user) {
    console.log('Welcome ' + user.email);
  } else {
    console.log('User signed out');
  }
});
firebase.auth().onAuthStateChanged();
medium
A. Missing semicolon after console.log statements
B. Using user.email is invalid; should use user.id
C. Calling onAuthStateChanged without a callback causes an error
D. No error; code works fine

Solution

  1. Step 1: Review the first observer usage

    The first call to onAuthStateChanged correctly passes a callback function.
  2. Step 2: Check the second call

    The second call to onAuthStateChanged has no callback, which is required and causes an error.
  3. Final Answer:

    Calling onAuthStateChanged without a callback causes an error -> Option C
  4. Quick Check:

    Callback required for onAuthStateChanged [OK]
Hint: Always provide a callback to onAuthStateChanged [OK]
Common Mistakes:
  • Thinking user.email is invalid (it is valid)
  • Ignoring missing callback error
  • Assuming missing semicolons cause runtime errors
5. You want your app to update the UI immediately when the user signs in or out, and also fetch user profile data only when signed in. Which approach using Firebase auth state observer is best?
hard
A. Use onAuthStateChanged to detect user, then fetch profile data inside the callback only if user exists
B. Fetch profile data once at app start, ignoring auth state changes
C. Use onAuthStateChanged but fetch profile data outside the callback unconditionally
D. Do not use onAuthStateChanged; instead poll user status every 5 seconds

Solution

  1. Step 1: Understand the need for immediate UI update

    Using onAuthStateChanged lets the app react instantly to sign-in or sign-out events.
  2. Step 2: Fetch profile data conditionally

    Fetching profile data inside the callback only when user exists avoids unnecessary calls and ensures data is current.
  3. Final Answer:

    Use onAuthStateChanged to detect user, then fetch profile data inside the callback only if user exists -> Option A
  4. Quick Check:

    Fetch profile inside auth callback if user present [OK]
Hint: Fetch profile only inside auth callback when user exists [OK]
Common Mistakes:
  • Fetching profile data regardless of auth state
  • Polling user status wastes resources
  • Ignoring auth state changes for UI updates
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