@oberoncms/core
Version:
OberonCMS is a cloud deployable CMS written in typescript based on the Puck visual editor
30 lines (29 loc) • 1.01 kB
JavaScript
import { useRef, useCallback } from "react";
import { useLocalStorage } from "@tohuhono/utils/use-local-storage";
import { encode } from "@tohuhono/utils";
function isData(value) {
return typeof value === "object" && value !== null && "content" in value && Array.isArray(value.content) && "root" in value;
}
const useLocalData = (path, config) => {
const componentKey = Object.keys(config.components).join("-");
const cachedSnapshot = useRef(null);
const key = `${encode(componentKey)}:${path}`;
const parser = useCallback((maybeData) => {
const cached = cachedSnapshot.current;
if (cached && cached.raw === maybeData) {
return cached.data;
}
try {
const rawParsed = maybeData ? JSON.parse(maybeData) : null;
const parsed = isData(rawParsed) ? rawParsed : null;
cachedSnapshot.current = { raw: maybeData, data: parsed };
return parsed;
} catch {
return null;
}
}, []);
return useLocalStorage(key, { parser });
};
export {
useLocalData
};