Fix ProtectedRoute blank page issue

Changed from useState to useRef for hasChecked flag to prevent loading state on route navigation. Each ProtectedRoute instance now properly renders immediately after auth check completes.

## Changes:
- Use useRef instead of useState for hasChecked flag
- Remove !hasChecked from loading condition
- This allows immediate rendering after first auth check
- Prevents blank pages when navigating between admin routes

## Technical Details:
- useState caused each new route to start with hasChecked=false
- useRef persists the check but each route instance is independent
- Combined with removing !hasChecked from loading check, pages render immediately

🤖 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:13:26 +07:00
parent e4a09a676e
commit 87539eb51f

View File

@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth';
import { Skeleton } from '@/components/ui/skeleton';
@@ -11,12 +11,12 @@ interface ProtectedRouteProps {
export function ProtectedRoute({ children, requireAdmin = false }: ProtectedRouteProps) {
const { user, loading: authLoading } = useAuth();
const navigate = useNavigate();
const [hasChecked, setHasChecked] = useState(false);
const hasCheckedRef = useRef(false);
useEffect(() => {
// Only run effect once after auth loading completes
if (!authLoading && !hasChecked) {
setHasChecked(true);
// Only run effect once per component mount
if (!authLoading && !hasCheckedRef.current) {
hasCheckedRef.current = true;
if (!user) {
// Save current URL to redirect back after login
@@ -36,10 +36,10 @@ export function ProtectedRoute({ children, requireAdmin = false }: ProtectedRout
}
}
}
}, [user, authLoading, navigate, requireAdmin, hasChecked]);
}, [user, authLoading, navigate, requireAdmin]);
// Show loading skeleton while checking auth
if (authLoading || !hasChecked) {
if (authLoading) {
return (
<div className="min-h-screen bg-background">
<div className="container mx-auto px-4 py-8">