-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflat-store.ts
43 lines (35 loc) · 1.12 KB
/
flat-store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { useRef } from "react";
import { createFlatStore, createFlatStoreOfSignals } from "../flat-store";
import { untracked } from "../utils";
import { useSignalEffectOnce } from "./utility";
export type AnyRecord = Record<any, any>;
/**
* Create a flat store and its setter.
*/
export const useFlatStore = <T extends AnyRecord>(storeCreator: () => T) => {
const storeRef = useRef<ReturnType<typeof createFlatStore<T>> | null>();
if (!storeRef.current) {
storeRef.current = createFlatStore(untracked(storeCreator));
}
return storeRef.current;
};
export const useFlatStoreOfSignals = <T extends AnyRecord>(
storeCreator: () => T
) => {
const storeRef = useRef<ReturnType<
typeof createFlatStoreOfSignals<T>
> | null>();
if (!storeRef.current) {
storeRef.current = createFlatStoreOfSignals(untracked(storeCreator));
}
return storeRef.current;
};
export const useComputedFlatStore = <T extends AnyRecord>(
storeUpdater: () => T
) => {
const [store, setStore] = useFlatStore(storeUpdater);
useSignalEffectOnce(() => {
setStore(storeUpdater());
});
return store as Readonly<typeof store>;
};