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;