Thuta Learning
IntermediateDevOps & ToolsIntermediate

Checking login state

Firebase TutorialLesson 9

Checking login state

An auth state listener lets your app know whether a user is logged in, has logged out, or is still logged in after a page refresh. Whether the navbar shows a Login button or a Dashboard depends on this state.

Code Example

javascript
import { getAuth, onAuthStateChanged } from 'firebase/auth';

const auth = getAuth();

const unsubscribe = onAuthStateChanged(auth, (user) => {
  if (user) {
    console.log('User is logged in:', user.uid);
  } else {
    console.log('No user. Show login page.');
  }
});

// Single-page app တွင် component မလိုတော့သောအခါ unsubscribe() ခေါ်နိုင်သည်။

What to watch out for

onAuthStateChanged also fires once when the app first loads. Because of that, it's better UX to keep a loading state and only render the page once you actually know whether a user exists.

Common mistake

If you keep re-attaching this listener inside a React/Vue component without cleaning it up, you can end up with a memory leak or duplicate console logs. Make sure to unsubscribe when the component unmounts.

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Checking login state | Thuta Learning