重构认证逻辑,优化登录和用户信息获取流程,新增全局缓存支持

This commit is contained in:
2025-04-23 19:00:53 +08:00
parent 22d3b8f3e3
commit 9473413def
23 changed files with 438 additions and 474 deletions

View File

@@ -0,0 +1,43 @@
'use client'
import {User} from '@/lib/models'
import {createContext, ReactNode, useContext, useRef} from 'react'
import {createProfileStore, ProfileStore} from '@/stores/profile-store'
import {StoreApi} from 'zustand/vanilla'
import {useStore} from 'zustand/react'
export type StoreContextType = {
profile: StoreApi<ProfileStore>
}
export const StoreContext = createContext<StoreContextType | null>(null)
export type ProfileProviderProps = {
user: User | null
children: ReactNode
}
export default function StoreProvider(props: ProfileProviderProps) {
const profile = useRef<StoreApi<ProfileStore>>(null)
if (!profile.current) {
console.log('create profile store')
profile.current = createProfileStore(props.user)
}
return (
<StoreContext.Provider value={{
profile: profile.current,
}}>
{props.children}
</StoreContext.Provider>
)
}
export function useProfileStore<T>(selector: (store: ProfileStore) => T) {
const ctx = useContext(StoreContext)
if (!ctx) {
throw new Error('useProfileStore must be used within a StoreProvider')
}
return useStore(ctx.profile, selector)
}