fix: prevent admin page reload redirect to dashboard

Wait for admin role check to complete before setting loading to false.
This prevents race condition where:
1. authLoading becomes false after session loads
2. isAdmin is still false (async check in progress)
3. Page redirects to /dashboard before isAdmin is set to true

Now loading stays true until BOTH session and admin role are loaded,
ensuring admin pages don't redirect on reload.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
dwindown
2025-12-27 23:55:46 +07:00
parent 79e1bd82fc
commit 0e3a45cfe2

View File

@@ -31,11 +31,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setUser(session?.user ?? null); setUser(session?.user ?? null);
if (session?.user) { if (session?.user) {
checkAdminRole(session.user.id); // Wait for admin role check before setting loading to false
checkAdminRole(session.user.id).then(() => {
if (mounted) setLoading(false);
});
} else {
// No session, set loading to false immediately
if (mounted) setLoading(false);
} }
// Only set loading to false after initial session is loaded
setLoading(false);
}); });
// Then listen for auth state changes // Then listen for auth state changes
@@ -47,13 +50,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setUser(session?.user ?? null); setUser(session?.user ?? null);
if (session?.user) { if (session?.user) {
checkAdminRole(session.user.id); // Wait for admin role check
checkAdminRole(session.user.id).then(() => {
if (mounted) setLoading(false);
});
} else { } else {
setIsAdmin(false); setIsAdmin(false);
// No session, set loading to false immediately
if (mounted) setLoading(false);
} }
// Ensure loading is false after auth state changes
setLoading(false);
} }
); );
@@ -72,6 +77,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
.maybeSingle(); .maybeSingle();
setIsAdmin(!!data); setIsAdmin(!!data);
return !!data; // Return the result
}; };
const signIn = async (email: string, password: string) => { const signIn = async (email: string, password: string) => {