移动USER_ME_CACHE_KEY到UserApi中、登出移除该缓存

This commit is contained in:
2025-06-19 09:15:03 +08:00
parent 3ac2a164a5
commit 00ce4850fa
3 changed files with 10 additions and 8 deletions

View File

@@ -28,31 +28,30 @@ export default function ConsoleMenuLayout({
const getInitialData = () => {
if (!window || !window.localStorage) return null;
const cache = localStorage.getItem(USER_ME_CACHE_KEY);
const cache = localStorage.getItem(UserApi.USER_ME_CACHE_KEY);
if (!cache) return;
try {
const user = JSON.parse(cache);
if (!user || !user.userId) throw new Error();
return user;
} catch (error) {
localStorage.removeItem(USER_ME_CACHE_KEY);
localStorage.removeItem(UserApi.USER_ME_CACHE_KEY);
}
return undefined;
}
const USER_ME_CACHE_KEY = 'user-me-cache';
const { data: user, isLoading, error } = useSWR(
'/api/user/me',
async () => {
const data = await UserApi.me();
localStorage.setItem(USER_ME_CACHE_KEY, JSON.stringify(data));
localStorage.setItem(UserApi.USER_ME_CACHE_KEY, JSON.stringify(data));
return data;
},
{
onError: (error) => {
if (error.statusCode === 401) {
localStorage.removeItem('token');
localStorage.removeItem(USER_ME_CACHE_KEY);
localStorage.removeItem(UserApi.USER_ME_CACHE_KEY);
toast.info('登录凭证已失效,请重新登录');
router.replace('/console/login');
}
@@ -67,7 +66,7 @@ export default function ConsoleMenuLayout({
if (!isLoading && !error && !user) {
router.replace('/console/login');
localStorage.removeItem('token');
localStorage.removeItem(USER_ME_CACHE_KEY);
localStorage.removeItem(UserApi.USER_ME_CACHE_KEY);
toast.error('账户状态异常,请重新登录');
}

View File

@@ -26,7 +26,7 @@ import {
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar"
import { authApi } from "@/lib/api"
import { authApi, UserApi } from "@/lib/api"
import { Skeleton } from "./ui/skeleton"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
@@ -42,6 +42,7 @@ export function NavUser({ user, isUserLoading }: { user: User | undefined, isUse
try {
await authApi.logout();
localStorage.removeItem('token');
localStorage.removeItem(UserApi.USER_ME_CACHE_KEY)
toast.success('登出成功');
router.replace('/console/login');
} catch (error) {

View File

@@ -3,4 +3,6 @@ import fetcher from "../fetcher";
export async function me() {
return fetcher<User>('/api/user/me');
}
}
export const USER_ME_CACHE_KEY = 'user-me-cache';