Files
web/src/components/providers/StoreProvider.tsx

59 lines
1.6 KiB
TypeScript

'use client'
import {User} from '@/lib/models'
import {createContext, ReactNode, useContext, useRef} from 'react'
import {StoreApi} from 'zustand/vanilla'
import {useStore} from 'zustand/react'
import {createProfileStore, ProfileStore} from '@/lib/stores/profile'
import {createLayoutStore, LayoutStore} from '@/lib/stores/layout'
export type StoreContextType = {
profile: StoreApi<ProfileStore>
layout: StoreApi<LayoutStore>
}
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)
}
const layout = useRef<StoreApi<LayoutStore>>(null)
if (!layout.current) {
console.log('📦 create layout store')
layout.current = createLayoutStore()
}
return (
<StoreContext.Provider value={{
profile: profile.current,
layout: layout.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)
}
export function useLayoutStore<T>(selector: (store: LayoutStore) => T) {
const ctx = useContext(StoreContext)
if (!ctx) {
throw new Error('useLayoutStore must be used within a StoreProvider')
}
return useStore(ctx.layout, selector)
}