- I created a route with the code below but I don't know how to implement login interception with lazy loading, I tried many ways.
- The main problem is that I'm using lazy loading mode and I'm using TypeScript.
- I also looked for related solutions on many websites, but none met my expectations.
- There is no relevant description of this problem in the official documentation, and there is no functional code similar to the route guard in Vue-Router.
const NotFound = lazy(() => import("@/page/error/NotFound"));
const UserLogin = lazy(() => import("@/page/login/UserLogin"));
const PageHome = lazy(() => import("@/page/home/PageHome"));
const PageFile = lazy(() => import("@/page/file/PageFile"));
const router = createBrowserRouter([
{
path: "/login",
Component: UserLogin,
},
{
path: "/",
Component: PageHome,
children: [
{
index: true,
Component: PageFile,
},
],
},
{
path: "*",
Component: NotFound,
},
]);
export default router;
I tried the following, but failed
import { FC, LazyExoticComponent } from "react";
import { useCookies } from "react-cookie";
import { Navigate, useLocation } from "react-router-dom";
interface AuthNode {
children: LazyExoticComponent<FC>;
}
const AuthRoute: FC<AuthNode> = ({ children }) => {
const [cookie] = useCookies<string>(["Authorization"]);
const location = useLocation();
if (location.pathname !== "/login" && !cookie) {
return <Navigate to={"/login"} state={{ from: location }} replace />;
}
return <>{children}</>;
};
export default AuthRoute;