jotai-ssr
Version:
Jotai utilities for server-side rendering (SSR)
34 lines (33 loc) • 1.53 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isHydratingAtom = void 0;
exports.useHydrateAtoms = useHydrateAtoms;
const jotai_1 = require("jotai");
const react_1 = require("react");
function useHydrateAtoms(hydrateAtoms, options) {
const isHydratedRef = (0, react_1.useRef)(false);
const lastHydrateAtoms = (0, react_1.useRef)(hydrateAtoms);
const store = (0, jotai_1.useStore)((options === null || options === void 0 ? void 0 : options.store) != null ? { store: options === null || options === void 0 ? void 0 : options.store } : undefined);
const hydrate = (0, react_1.useCallback)(() => {
store.set(isHydratingPrimitiveAtom, true);
for (const [atom, ...args] of hydrateAtoms) {
store.set(atom, ...args);
}
store.set(isHydratingPrimitiveAtom, false);
isHydratedRef.current = true;
}, [store, hydrateAtoms]);
if (!isHydratedRef.current) {
hydrate();
}
(0, react_1.useEffect)(() => {
if (!(options === null || options === void 0 ? void 0 : options.enableReHydrate)) {
return;
}
if (hydrateAtoms !== lastHydrateAtoms.current) {
lastHydrateAtoms.current = hydrateAtoms;
hydrate();
}
}, [hydrate, options === null || options === void 0 ? void 0 : options.enableReHydrate, hydrateAtoms]);
}
const isHydratingPrimitiveAtom = (0, jotai_1.atom)(false);
exports.isHydratingAtom = (0, jotai_1.atom)((get) => get(isHydratingPrimitiveAtom));