skip to Main Content

I’m doing an email verification system using Firebase.
So basically, I made a page which sign up, then sign in a user.

I get the user like so :

import {useAuthState} from "react-firebase-hooks/auth";

const [user, loading, error] = useAuthState(FirebaseAuth)

On the next page I ask the user to check his mails, because I sent a confirmation mail.

I’m using a useEffect hook, with [user] as dependency, where I console.log("test").
The useEffect is never called except at the mount of the page.

And yet, in the background, the email of the user is verified, so useEffect should get executed since user.emailVerified changed.

I also tried to use onAuthStateChanged, but user was remaining to "null", even after the email got verified…. :

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

  useEffect(() => {
    const auth = getAuth(firebase_app);

    const unsubscribe = onAuthStateChanged(auth, (authUser) => {
      if (authUser) {
        setUser(authUser);
      }
    });


    return () => unsubscribe();
  }, []);

2

Answers


  1. I’m not 100% sure but I think this a ‘context’ issue where your logic is still using an ‘old’ context/reference.

    Here’s how I’ve managed the email confirmation in the past:

      let emailInterval = useRef<NodeJS.Timer>();
      useEffect(() => {
        emailInterval.current = setInterval(async () => {
          // Make sure we have the most recent version of the current user after
          // they've confirmed their email
          await auth().currentUser?.reload();
    
          // Check if the user had confirmed their email
          if (auth().currentUser?.emailVerified) {
            handleEmailVerified();
          } else {
            if (!emailConfirmationHasBeenSent) {
              sendEmailConfirmation();
            }
          }
        }, 5000);
    
        return () => clearEmailInterval();
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, []);
    
      const clearEmailInterval = () => {
        if (emailInterval.current) {
          clearInterval(emailInterval.current);
        }
      };
    
    Login or Signup to reply.
  2. Email verification happens out-of-band, as it happens in the users email client or in their browser, and not in your application. This means that your application won’t know about the change in verification state, until it refreshes the ID token of the users, which is does:

    • When the user signs-in again.
    • Automatically once every hour, a few minutes before the current ID token expires.
    • When you force it to refresh the ID token by calling reload() or getIdToken(true) on the user.

    This has been covered before, so also have a look at:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search