Simplify ProtectedRoute to fix blank page issue

Removed hasChecked ref logic that was causing rendering issues. The key insight is that the effect should run when user changes, but only redirect if the condition doesn't match.

## Changes:
- Remove hasCheckedRef complexity
- Simplify effect to only redirect when conditions don't match
- Split admin check into separate condition that only runs when user exists
- This prevents unnecessary redirects while allowing normal rendering

## Root Cause:
The hasChecked logic was preventing the component from rendering properly on navigation.

🤖 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
2026-01-04 18:21:06 +07:00
parent 87539eb51f
commit a423a6d31d

View File

@@ -1,4 +1,4 @@
import { useEffect, useRef } from 'react'; import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth'; import { useAuth } from '@/hooks/useAuth';
import { Skeleton } from '@/components/ui/skeleton'; import { Skeleton } from '@/components/ui/skeleton';
@@ -11,14 +11,9 @@ interface ProtectedRouteProps {
export function ProtectedRoute({ children, requireAdmin = false }: ProtectedRouteProps) { export function ProtectedRoute({ children, requireAdmin = false }: ProtectedRouteProps) {
const { user, loading: authLoading } = useAuth(); const { user, loading: authLoading } = useAuth();
const navigate = useNavigate(); const navigate = useNavigate();
const hasCheckedRef = useRef(false);
useEffect(() => { useEffect(() => {
// Only run effect once per component mount if (!authLoading && !user) {
if (!authLoading && !hasCheckedRef.current) {
hasCheckedRef.current = true;
if (!user) {
// Save current URL to redirect back after login // Save current URL to redirect back after login
const currentPath = window.location.pathname + window.location.search; const currentPath = window.location.pathname + window.location.search;
sessionStorage.setItem('redirectAfterLogin', currentPath); sessionStorage.setItem('redirectAfterLogin', currentPath);
@@ -26,14 +21,12 @@ export function ProtectedRoute({ children, requireAdmin = false }: ProtectedRout
return; return;
} }
// Check for admin role if required // Check for admin role if required (only after user is loaded)
if (requireAdmin) { if (!authLoading && user && requireAdmin) {
const userRole = user.user_metadata?.role; const userRole = user.user_metadata?.role;
if (userRole !== 'admin') { if (userRole !== 'admin') {
// Redirect non-admin users to member dashboard // Redirect non-admin users to member dashboard
navigate('/dashboard'); navigate('/dashboard');
return;
}
} }
} }
}, [user, authLoading, navigate, requireAdmin]); }, [user, authLoading, navigate, requireAdmin]);