Skip to content

Commit

Permalink
Add an authStateIsLoading flag
Browse files Browse the repository at this point in the history
  • Loading branch information
kamarmack committed Dec 25, 2023
1 parent bf4af26 commit c401621
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
8 changes: 7 additions & 1 deletion src/features/authentication/hooks/useAuthStateRedirect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export const useAuthStateRedirect = (
// Redirect to Authenticated User Welcome Page if User is Authenticated and Authenticated Users are not allowed
useEffect(() => {
if (!router.isReady) return;
if (authContext.authStateIsLoading) return;

if (authContext.user) {
if (allowAuthenticatedUsers) return;
Expand All @@ -79,7 +80,12 @@ export const useAuthStateRedirect = (

redirectToLoginPage({ ...options, router });
return;
}, [authContext.user, client_token, router.isReady]);
}, [
authContext.authStateIsLoading,
authContext.user,
client_token,
router.isReady,
]);

return { ...authContext };
};
35 changes: 27 additions & 8 deletions src/features/authentication/providers/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,44 @@ import { firebaseApp } from '../../../lib/firebase';

const auth = getAuth(firebaseApp);

export const AuthContext = createContext<{ user: FirebaseUser | null }>({
export type AuthProviderState = {
authStateIsLoading: boolean;
user: FirebaseUser | null;
};
export const AuthContext = createContext<AuthProviderState>({
authStateIsLoading: true,
user: null,
});

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
const [authStateIsLoading, setAuthStateIsLoading] = useState(true);
const [user, setUser] = useState<FirebaseUser | null>(null);

useEffect(() => {
auth
.authStateReady()
.then(() => {
setAuthStateIsLoading(false);
return;
})
.catch((error) => {
console.error(error);
});
}, []);

useEffect(() => {
if (authStateIsLoading) return;

const unsubscribe = auth.onAuthStateChanged((user) => {
if (user) {
setUser(() => user);
} else {
setUser(null);
}
setUser(() => user);
});

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

return (
<AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
<AuthContext.Provider value={{ authStateIsLoading, user }}>
{children}
</AuthContext.Provider>
);
};

0 comments on commit c401621

Please sign in to comment.