How do I implement Firebase authentication with local state with hooks?

Viewed 671

I was following using-firebaseauth-with-local-state to implement authentication in my react app but I am using functional components and hooks. How am I supposed to implement the componentDidMount() and componentWillUnmount()?

Here is the code I have in the Login.jsx component:

import React, { useState, useEffect } from 'react'

import StyledFirebaseAuth from "react-firebaseui/StyledFirebaseAuth";
import firebase from "firebase";


// Configure Firebase.
const config = {
  apiKey: "myapikey",
  authDomain: "mydomain.firebaseapp.com"
  // ...
};
firebase.initializeApp(config);

// Configure FirebaseUI.
const uiConfig = {
  // Popup signin flow rather than redirect flow.
  signInFlow: "popup",
  // Redirect to /signedIn after sign in is successful. Alternatively you can provide a callbacks.signInSuccess function.
  signInSuccessUrl: "/",
  // We will display Google and Facebook as auth providers.
  signInOptions: [
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
    firebase.auth.FacebookAuthProvider.PROVIDER_ID
  ],
  callbacks: {
    // Avoid redirects after sign-in.
    signInSuccessWithAuthResult: () => false
  }
};

export default function Login() {
  const [signedIn, setSignIn]= useState(false);

  useEffect(() => {
    return () => {
    const unregisterAuthObserver = firebase.auth().onAuthStateChanged(
        (user) => setSignIn({isSignedIn: !!user})
    );
    unregisterAuthObserver();
    console.log("Sdd")
    };
  })

  if (!signedIn) {
    return (
      <div>
        <h1>My App</h1>
        <p>Please sign-in:</p>
        <StyledFirebaseAuth
          uiConfig={uiConfig}
          firebaseAuth={firebase.auth()}
        />
      </div>
    );
  }

  return (
    <div>
      <h1>My App</h1>
      <p>Welcome {firebase.auth().currentUser.displayName}! You are now signed-in!</p>
      <a onClick={() => firebase.auth().signOut()}>Sign-out</a>
    </div>
  );
}
1 Answers

How am I supposed to implement the componentDidMount() and componentWillUnmount()?

Use useEffect with an empty array to emulate a componentDidMount; then return a function from that same useEffect to emulate componentWillUnmount.

In your code, useEffect return a function, so that means that this function will execute when the component will get unmounted, so your firebase.auth().onAuthStateChanged will get hooked when you'll done with the Login component.

To make a proper hook, set useEffect like this:

useEffect(() => {

  const unregisterAuthObserver = firebase.auth()
    .onAuthStateChanged(
      (user) => setSignIn({isSignedIn: !!user})
    );

  // Now you either return just unregisterAuthObserver
  // which will be called when the component is unmounted
  return unregisterAuthObserver;

  // or you create a function if you want more login when the component is unmounted
  // return () => {
  //   unregisterAuthObserver();
  //   console.log("Sdd");
  // }

}, []); // Important, pass an empty array so to execute useEffect hook only once
Related