From da1b27d3e6dc8b607b3d9629946eabc970cf0100 Mon Sep 17 00:00:00 2001 From: Oliver Pan <2216991777@qq.com> Date: Mon, 24 Jun 2024 00:33:52 -0500 Subject: [PATCH] feat: new zustand store hydration method --- apps/web/context/color-store-provider.tsx | 31 +++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 apps/web/context/color-store-provider.tsx diff --git a/apps/web/context/color-store-provider.tsx b/apps/web/context/color-store-provider.tsx new file mode 100644 index 0000000..8da3dab --- /dev/null +++ b/apps/web/context/color-store-provider.tsx @@ -0,0 +1,31 @@ +'use client' + +import { createContext, useContext, useRef } from 'react' + +import { ColorStore, ColorsHydrateValues, createColorStore } from '@/store/store' +import { useStore } from 'zustand' + +export type ColorStoreApi = ReturnType + +const ColorStoreContext = createContext(null) + +export interface ColorStoreProviderProps extends ColorsHydrateValues { + children: any +} + +export function ColorStoreProvider({ children, ...rest }: ColorStoreProviderProps) { + const storeRef = useRef() + if (!storeRef.current) { + storeRef.current = createColorStore(rest) + } + + return {children} +} + +export const useColorStore = (selector: (store: ColorStore) => T): T => { + const storeContent = useContext(ColorStoreContext) + if (!storeContent) { + throw new Error('useColorStore must be used within a ColorStoreProvider') + } + return useStore(storeContent, selector) +}