mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-06 07:36:37 +08:00
个人信息页面增强
This commit is contained in:
@@ -1,69 +1,20 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { ConfigService, PublicConfigResponse } from '@/lib/services'
|
||||
|
||||
/* 全局缓存 */
|
||||
let cachedConfig: PublicConfigResponse | null = null
|
||||
let cachePromise: Promise<PublicConfigResponse> | null = null
|
||||
let cacheTime = 0
|
||||
const CACHE_DURATION = 5 * 60 * 1000
|
||||
import {useQuery} from '@tanstack/react-query'
|
||||
import {ConfigService} from '@/lib/services'
|
||||
|
||||
/**
|
||||
* 获取公共配置(带缓存)
|
||||
*
|
||||
* 获取公共配置(使用 React Query 进行统一缓存与自动同步)
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { config, loading, error } = usePublicConfig()
|
||||
* ```
|
||||
*/
|
||||
export function usePublicConfig() {
|
||||
const [config, setConfig] = useState<PublicConfigResponse | null>(cachedConfig)
|
||||
const [loading, setLoading] = useState(!cachedConfig)
|
||||
const [error, setError] = useState<Error | null>(null)
|
||||
const { data: config, isLoading: loading, error } = useQuery({
|
||||
queryKey: ['public-config'],
|
||||
queryFn: () => ConfigService.getPublicConfig(),
|
||||
staleTime: 5 * 60 * 1000, // 5 分钟缓存
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true
|
||||
|
||||
const fetchConfig = async () => {
|
||||
const now = Date.now()
|
||||
|
||||
if (cachedConfig && (now - cacheTime) < CACHE_DURATION) {
|
||||
if (mounted) {
|
||||
setConfig(cachedConfig)
|
||||
setLoading(false)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!cachePromise) {
|
||||
cachePromise = ConfigService.getPublicConfig()
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await cachePromise
|
||||
if (mounted) {
|
||||
cachedConfig = data
|
||||
cacheTime = now
|
||||
setConfig(data)
|
||||
setError(null)
|
||||
}
|
||||
} catch (err) {
|
||||
if (mounted) {
|
||||
setError(err instanceof Error ? err : new Error('获取配置失败'))
|
||||
}
|
||||
} finally {
|
||||
cachePromise = null
|
||||
if (mounted) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fetchConfig()
|
||||
|
||||
return () => {
|
||||
mounted = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
return { config, loading, error }
|
||||
return { config: config || null, loading, error }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user