fix: refresh auth roles promptly

This commit is contained in:
yun-zhi-ztl 2026-03-16 17:31:53 +08:00
parent dee07ad7a2
commit cb9c2f489b
2 changed files with 27 additions and 5 deletions

View file

@ -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)
})
})

View file

@ -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<User | null>({
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<User | null>(getAuthQueryOptions(enabled))
return {
user: user ?? null,