'Multiple Guard on single route React

Can you put multiple route guards on one route? I'm trying to put two guards (one is auth and other is roleguard) on "/main/dashboard" so that it can only be accessed by specific roles. Below is my code. It's not working.

{
  path: '/main/dashboard',
  element: (
    <AuthGuard>
      <RoleGuard role={GUEST}>
        <DashboardLayout />
      </RoleGuard>
    </AuthGuard>
  ),
  children: [
    { element: <Navigate to={LoginPath()} replace />, index: true },
    { path: 'dashboard', element: <Dashboard /> },
  ],
},

RoleGuard Component here

  import { ReactNode } from 'react';
  import useAuth from 'src/hooks/useAuth';
  import LoginView from 'src/components/auth/login/LoginView';


  type RoleBasedGuardProp = {
  role: string;
  children: ReactNode | string;
  };

  export default function RoleBasedGuard({ role, children }:  RoleBasedGuardProp) {
  const { user } = useAuth();

  if (user?.account_type === role) {
   return <LoginView />;
  }
  return <>{children}</>;
  }

AuthGuard Component Here (Basically authentication for users)

import { useState, ReactNode } from 'react';
import { Navigate, useLocation } from 'react-router-dom';

import useAuth from '../hooks/useAuth';
import LoginView from 'src/components/auth/login/LoginView';
import LoadingScreen from '../components/LoadingScreen';


 type AuthGuardProps = {
 children: ReactNode;
 };

 export default function AuthGuard({ children }: AuthGuardProps) {
  const { isAuthenticated, isInitialized } = useAuth();
  const { pathname } = useLocation();
  const [requestedLocation, setRequestedLocation] = useState<string | null>(null);

  if (!isInitialized) {
  return <LoadingScreen />;
  }

  if (!isAuthenticated) {
  if (pathname !== requestedLocation) {
  setRequestedLocation(pathname);
  }
 return <LoginView />;
 }

 if (requestedLocation && pathname !== requestedLocation) {
 setRequestedLocation(null);
 return <Navigate to={requestedLocation} />;
 }

 return <>{children}</>;
 }



 


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source