提升userMe到hook中
This commit is contained in:
@@ -12,38 +12,26 @@ import {
|
|||||||
SidebarProvider,
|
SidebarProvider,
|
||||||
SidebarTrigger,
|
SidebarTrigger,
|
||||||
} from "@/components/ui/sidebar"
|
} from "@/components/ui/sidebar"
|
||||||
|
import { useUserMe } from "@/hooks/user/use-user-me";
|
||||||
import { UserApi } from "@/lib/api";
|
import { UserApi } from "@/lib/api";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useEffect, useLayoutEffect } from "react";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import useSWR from "swr";
|
|
||||||
|
|
||||||
export default function ConsoleMenuLayout({
|
export default function ConsoleMenuLayout({
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
children: React.ReactNode
|
children: React.ReactNode
|
||||||
}) {
|
}) {
|
||||||
const isClientSide = typeof window !== 'undefined';
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const { data: user, isLoading, error, mutate } = useSWR(
|
const { user, isLoading, error } = useUserMe({
|
||||||
'/api/user/me',
|
onError: (e) => {
|
||||||
async () => UserApi.me(),
|
if (e.statusCode === 401) {
|
||||||
{
|
toast.info('登录凭证已失效,请重新登录');
|
||||||
onError: (error) => {
|
router.replace('/console/login');
|
||||||
if (error.statusCode === 401) {
|
}
|
||||||
if (isClientSide) {
|
|
||||||
localStorage.removeItem('token');
|
|
||||||
}
|
|
||||||
toast.info('登录凭证已失效,请重新登录');
|
|
||||||
router.replace('/console/login');
|
|
||||||
}
|
|
||||||
},
|
|
||||||
revalidateIfStale: false,
|
|
||||||
revalidateOnFocus: false,
|
|
||||||
revalidateOnReconnect: false,
|
|
||||||
}
|
}
|
||||||
);
|
});
|
||||||
|
|
||||||
if (!isLoading && !error && !user) {
|
if (!isLoading && !error && !user) {
|
||||||
router.replace('/console/login');
|
router.replace('/console/login');
|
||||||
|
|||||||
30
tone-page-web/hooks/user/use-user-me.ts
Normal file
30
tone-page-web/hooks/user/use-user-me.ts
Normal 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
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user