更新
This commit is contained in:
48
frontend/src/router/dynamic-router.ts
Normal file
48
frontend/src/router/dynamic-router.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { fetchDynamicRoutes } from "@/api";
|
||||
import { isAuthenticated, signOut } from "@/store";
|
||||
import type { RouteNode } from "@/types";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export interface DynamicRouterData {
|
||||
authed: boolean;
|
||||
loading: boolean;
|
||||
loadError: boolean;
|
||||
dynamicRoutes: RouteNode[];
|
||||
}
|
||||
|
||||
export function useDynamicRouterData(): DynamicRouterData {
|
||||
const authed = isAuthenticated();
|
||||
const [dynamicRoutes, setDynamicRoutes] = useState<RouteNode[]>([]);
|
||||
const [loading, setLoading] = useState(authed);
|
||||
const [loadError, setLoadError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!authed) {
|
||||
setDynamicRoutes([]);
|
||||
setLoading(false);
|
||||
setLoadError(false);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setLoadError(false);
|
||||
fetchDynamicRoutes()
|
||||
.then((routes) => {
|
||||
setDynamicRoutes(routes);
|
||||
if (!routes || routes.length === 0) {
|
||||
setLoadError(true);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
setLoadError(true);
|
||||
signOut();
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [authed]);
|
||||
|
||||
return {
|
||||
authed,
|
||||
loading,
|
||||
loadError,
|
||||
dynamicRoutes
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user