GoogleAuthProvider does not persist/keep the login on refresh
here's the approach I've followed in one of my projects. I created a custom hook where I look for onAuthStateChanged
. Now, even if you refresh the auth'ed user would be persisted.
import { useEffect, useRef, useState } from 'react';
import { getAuth, onAuthStateChanged, User } from '@firebase/auth';
import { app } from '../../configuration/FirebaseConfiguration';
const useAuth = () => {
const [user, setUser] = useState<User | null>(null);
const auth = getAuth(app);
let mounted = useRef<boolean>(false);
useEffect(() => {
mounted.current = true;
const unsubscribe = onAuthStateChanged(auth, (user) => {
console.log("onAuthUserChanged", user);
if (user) {
if (mounted.current) {
setUser(user);
}
} else {
if (mounted.current) {
setUser(null);
}
}
});
return () => {
mounted.current = false;
unsubscribe();
};
}, [auth]);
return {
user,
auth,
};
};
export { useAuth };
Here's a link to a sample github repository I created a while back https://github.com/SangeetAgarwal/FirebaseAuthReactRouterv6