0

I used Firebase Authentication in my ReactJS Application, Since the user login to the application. Firebase onAuthStateChanged method triggering two times, what went this approach, Thanks in advance

AuthRoute

import React, { useEffect, useState } from 'react';
import { getAuth, onAuthStateChanged, User } from 'firebase/auth';
import { useNavigate } from 'react-router-dom';
import { RiseLoader } from 'react-spinners';
import ErrorPage from '../Pages/ErrorPage';

export interface IAuthRouteProps {
    children: React.ReactNode;
    onTokenReceived: (token: string) => void;
}

const AuthRoute: React.FunctionComponent<IAuthRouteProps> = ({ children, onTokenReceived }) => {
  
    const auth = getAuth();
    const navigate = useNavigate();
    const [loading, setLoading] = useState(true);
    const [errorMessage, setErrorMessage] = useState("");
    
    //#
    useEffect(() => {
      try {
        setErrorMessage("");
      
        const unsubscribe =onAuthStateChanged(auth, async (user: User | null) => {
          unsubscribe();
            if (user) {
              console.log('triggering routes -@c1');
              const token = await user.getIdToken(true);
              setLoading(false); 
              onTokenReceived(token); 
            
            } else {
              console.log('unauthorized');
              navigate('/login');
            }
        });
        
      } catch (error) {
        setErrorMessage("Authentication issue");
      }
        
      }, []); 
    //#
  
    if (loading) return <div className="mainHome">
    <RiseLoader className="progressStyle" color="#5AA5F5" size={16} />
    {errorMessage.length > 1 ? <ErrorPage message={''} code={0} /> :<></>}
</div>;
  
    return <>{children}</>;
  };
  
  export default AuthRoute;
FGH
  • 2,900
  • 6
  • 26
  • 59
  • 2
    What cersion of react are you using? If you are in dev and have strict mode enabled, `useEffect` hooks get executed twice https://react.dev/blog/2022/03/29/react-v18#new-strict-mode-behaviors – Jackson Aug 17 '23 at 04:31
  • Great, once i commented the strict mode, it's only triggering one time, thanks a lot,huge help – FGH Aug 17 '23 at 04:38

0 Answers0