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