Home > Enterprise >  How to check if user is logged in or not using firebase v9 (web)
How to check if user is logged in or not using firebase v9 (web)

Time:01-26

I want to render a login button if the user isn't signed in, otherwise I want to display a link to their profile how do I do this using firebase v9?

CodePudding user response:

You can use the Firebase Authentication API to check if a user is currently signed in, and then use this information to conditionally render the login button or the link to the user's profile.

Here is an example of how you could do this in a React functional component using the useEffect hook:

import { useEffect, useState } from 'react';
import firebase from 'firebase/app';
import 'firebase/auth';

function MyComponent() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const unsubscribe = firebase.auth().onAuthStateChanged(user => {
      if (user) {
        setUser(user);
      } else {
        setUser(null);
      }
    });
    return () => unsubscribe();
  }, []);

  return (
    <div>
      {user ? (
        <a href={`/profile/${user.uid}`}>Your Profile</a>
      ) : (
         <button onClick={() => firebase.auth().signInWithPopup(new
 firebase.auth.GoogleAuthProvider())}>
          Sign in with Google
        </button>
      )}
    </div>
  );
}

In this example, we use the useEffect hook to listen for changes to the user's authentication state. When the component mounts, we set up a listener using firebase.auth().onAuthStateChanged(), which will fire every time the user's authentication state changes (e.g. when they sign in or out). We use the setUser function to update the component's state with the current user object, or null if no user is signed in.

In the component's render method, we use a ternary operator to conditionally render the login button or the link to the user's profile, depending on whether the user state is null or not.

In the above example, I've used the google sign-in method, You can use any other sign-in method provided by firebase as well.

  • Related