diff options
Diffstat (limited to 'excalidraw-app/app-jotai.ts')
| -rw-r--r-- | excalidraw-app/app-jotai.ts | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/excalidraw-app/app-jotai.ts b/excalidraw-app/app-jotai.ts new file mode 100644 index 0000000..1591803 --- /dev/null +++ b/excalidraw-app/app-jotai.ts @@ -0,0 +1,37 @@ +// eslint-disable-next-line no-restricted-imports +import { + atom, + Provider, + useAtom, + useAtomValue, + useSetAtom, + createStore, + type PrimitiveAtom, +} from "jotai"; +import { useLayoutEffect } from "react"; + +export const appJotaiStore = createStore(); + +export { atom, Provider, useAtom, useAtomValue, useSetAtom }; + +export const useAtomWithInitialValue = < + T extends unknown, + A extends PrimitiveAtom<T>, +>( + atom: A, + initialValue: T | (() => T), +) => { + const [value, setValue] = useAtom(atom); + + useLayoutEffect(() => { + if (typeof initialValue === "function") { + // @ts-ignore + setValue(initialValue()); + } else { + setValue(initialValue); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + return [value, setValue] as const; +}; |
