From cb9c2f489b5743ba7ea4325e4c0a8f2be7867694 Mon Sep 17 00:00:00 2001 From: yun-zhi-ztl <15071461069@163.com> Date: Mon, 16 Mar 2026 17:31:53 +0800 Subject: [PATCH] fix: refresh auth roles promptly --- web/src/features/auth/use-auth.test.ts | 15 +++++++++++++++ web/src/features/auth/use-auth.ts | 17 ++++++++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) create mode 100644 web/src/features/auth/use-auth.test.ts diff --git a/web/src/features/auth/use-auth.test.ts b/web/src/features/auth/use-auth.test.ts new file mode 100644 index 00000000..49bb858a --- /dev/null +++ b/web/src/features/auth/use-auth.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest' +import { getAuthQueryOptions } from './use-auth' + +describe('getAuthQueryOptions', () => { + it('keeps auth state fresh so role changes are picked up promptly', () => { + const options = getAuthQueryOptions(true) + + expect(options.queryKey).toEqual(['auth', 'me']) + expect(options.staleTime).toBe(0) + expect(options.refetchOnWindowFocus).toBe(true) + expect(options.refetchOnReconnect).toBe(true) + expect(options.refetchInterval).toBe(60_000) + expect(options.enabled).toBe(true) + }) +}) diff --git a/web/src/features/auth/use-auth.ts b/web/src/features/auth/use-auth.ts index 54fbf84f..4a9d66d5 100644 --- a/web/src/features/auth/use-auth.ts +++ b/web/src/features/auth/use-auth.ts @@ -2,14 +2,21 @@ import { useQuery } from '@tanstack/react-query' import { authApi } from '@/api/client' import type { User } from '@/api/types' -export function useAuth(enabled = true) { - const { data: user, isLoading, error } = useQuery({ - queryKey: ['auth', 'me'], +export function getAuthQueryOptions(enabled = true) { + return { + queryKey: ['auth', 'me'] as const, queryFn: authApi.getMe, retry: false, enabled, - staleTime: 5 * 60 * 1000, // 5 分钟 - }) + staleTime: 0, + refetchOnWindowFocus: true, + refetchOnReconnect: true, + refetchInterval: 60_000, + } +} + +export function useAuth(enabled = true) { + const { data: user, isLoading, error } = useQuery(getAuthQueryOptions(enabled)) return { user: user ?? null,