|
1 | 1 | import { createContext, useContext } from 'react' |
2 | 2 | import { createStore, useStore as useZustandStore } from 'zustand' |
| 3 | +import { PreloadedStoreInterface } from './storeProvider' |
3 | 4 |
|
4 | | -interface StoreInterface { |
| 5 | +export interface StoreInterface { |
5 | 6 | lastUpdate: number |
6 | 7 | light: boolean |
7 | 8 | count: number |
8 | | - tick: (lastUpdate: number, light: boolean) => void |
| 9 | + tick: (lastUpdate: number) => void |
9 | 10 | increment: () => void |
10 | 11 | decrement: () => void |
11 | 12 | reset: () => void |
12 | 13 | } |
13 | 14 |
|
14 | | -const getDefaultInitialState = () => ({ |
15 | | - lastUpdate: Date.now(), |
16 | | - light: false, |
17 | | - count: 0, |
18 | | -}) |
| 15 | +function getDefaultInitialState() { |
| 16 | + return { |
| 17 | + lastUpdate: new Date(1970, 1, 1).getTime(), |
| 18 | + light: false, |
| 19 | + count: 0, |
| 20 | + } as const |
| 21 | +} |
19 | 22 |
|
20 | 23 | export type StoreType = ReturnType<typeof initializeStore> |
21 | 24 |
|
22 | | -const zustandContext = createContext<StoreType | null>(null) |
| 25 | +const storeContext = createContext<StoreType | null>(null) |
23 | 26 |
|
24 | | -export const Provider = zustandContext.Provider |
| 27 | +export const Provider = storeContext.Provider |
25 | 28 |
|
26 | | -export const useStore = <T>(selector: (state: StoreInterface) => T) => { |
27 | | - const store = useContext(zustandContext) |
| 29 | +export function useStore<T>(selector: (state: StoreInterface) => T) { |
| 30 | + const store = useContext(storeContext) |
28 | 31 |
|
29 | 32 | if (!store) throw new Error('Store is missing the provider') |
30 | 33 |
|
31 | 34 | return useZustandStore(store, selector) |
32 | 35 | } |
33 | 36 |
|
34 | | -export const initializeStore = ( |
35 | | - preloadedState: Partial<StoreInterface> = {} |
36 | | -) => { |
| 37 | +export function initializeStore(preloadedState: PreloadedStoreInterface) { |
37 | 38 | return createStore<StoreInterface>((set, get) => ({ |
38 | 39 | ...getDefaultInitialState(), |
39 | 40 | ...preloadedState, |
40 | | - tick: (lastUpdate, light) => { |
| 41 | + tick: (lastUpdate) => |
41 | 42 | set({ |
42 | 43 | lastUpdate, |
43 | | - light: !!light, |
44 | | - }) |
45 | | - }, |
46 | | - increment: () => { |
| 44 | + light: !get().light, |
| 45 | + }), |
| 46 | + increment: () => |
47 | 47 | set({ |
48 | 48 | count: get().count + 1, |
49 | | - }) |
50 | | - }, |
51 | | - decrement: () => { |
| 49 | + }), |
| 50 | + decrement: () => |
52 | 51 | set({ |
53 | 52 | count: get().count - 1, |
54 | | - }) |
55 | | - }, |
56 | | - reset: () => { |
| 53 | + }), |
| 54 | + reset: () => |
57 | 55 | set({ |
58 | 56 | count: getDefaultInitialState().count, |
59 | | - }) |
60 | | - }, |
| 57 | + }), |
61 | 58 | })) |
62 | 59 | } |
0 commit comments