重构认证逻辑,优化登录和用户信息获取流程,新增全局缓存支持
This commit is contained in:
43
src/components/providers/StoreProvider.tsx
Normal file
43
src/components/providers/StoreProvider.tsx
Normal 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)
|
||||
}
|
||||
Reference in New Issue
Block a user