提升userMe到hook中

This commit is contained in:
2025-06-19 15:01:08 +08:00
parent da16bc1dbe
commit cb2258aa64
2 changed files with 38 additions and 20 deletions

View File

@@ -12,38 +12,26 @@ import {
SidebarProvider,
SidebarTrigger,
} from "@/components/ui/sidebar"
import { useUserMe } from "@/hooks/user/use-user-me";
import { UserApi } from "@/lib/api";
import { useRouter } from "next/navigation";
import { useEffect, useLayoutEffect } from "react";
import { toast } from "sonner";
import useSWR from "swr";
export default function ConsoleMenuLayout({
children,
}: {
children: React.ReactNode
}) {
const isClientSide = typeof window !== 'undefined';
const router = useRouter();
const { data: user, isLoading, error, mutate } = useSWR(
'/api/user/me',
async () => UserApi.me(),
{
onError: (error) => {
if (error.statusCode === 401) {
if (isClientSide) {
localStorage.removeItem('token');
}
const { user, isLoading, error } = useUserMe({
onError: (e) => {
if (e.statusCode === 401) {
toast.info('登录凭证已失效,请重新登录');
router.replace('/console/login');
}
},
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
);
});
if (!isLoading && !error && !user) {
router.replace('/console/login');

View File

@@ -0,0 +1,30 @@
import { UserApi } from "@/lib/api";
import useSWR from "swr";
export function useUserMe({ onError }: { onError?: (e: any) => void } = {}) {
const isClientSide = typeof window !== 'undefined';
const { data: user, isLoading, error } = useSWR(
'/api/user/me',
async () => UserApi.me(),
{
onError: (error) => {
if (error.statusCode === 401) {
if (isClientSide) {
localStorage.removeItem('token');
}
}
onError?.(error);
},
revalidateIfStale: false,
revalidateOnFocus: false,
}
);
return {
user,
isLoading,
error
}
}