2023-02-22 15:01:23 +01:00
|
|
|
import { PrimitiveAtom, unstable_createStore, useAtom } from "jotai";
|
2022-07-05 16:03:40 +02:00
|
|
|
import { useLayoutEffect } from "react";
|
2022-04-20 14:40:03 +02:00
|
|
|
|
|
|
|
export const jotaiScope = Symbol();
|
|
|
|
export const jotaiStore = unstable_createStore();
|
2022-07-05 16:03:40 +02:00
|
|
|
|
|
|
|
export const useAtomWithInitialValue = <
|
|
|
|
T extends unknown,
|
2023-02-22 15:01:23 +01:00
|
|
|
A extends PrimitiveAtom<T>,
|
2022-07-05 16:03:40 +02:00
|
|
|
>(
|
|
|
|
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;
|
|
|
|
};
|