UNPKG

@croct/plug-react

Version:

React components and hooks to plug your React applications into Croct.

63 lines (62 loc) 1.64 kB
"use client"; import { useEffect, useState } from "react"; import { useLoader } from "./useLoader.js"; import { useCroct } from "./useCroct.js"; import { isSsr } from "../ssr-polyfills.js"; import { hash } from "../hash.js"; function useCsrEvaluation(query, options = {}) { const { cacheKey, fallback, expiration, staleWhileLoading = false, initial: initialValue, ...evaluationOptions } = options; const [initial, setInitial] = useState(initialValue); const croct = useCroct(); const result = useLoader({ cacheKey: hash( `useEvaluation:${cacheKey ?? ""}:${query}:${JSON.stringify(options.attributes ?? {})}` ), loader: () => croct.evaluate(query, cleanEvaluationOptions(evaluationOptions)), initial, fallback, expiration }); useEffect( () => { if (staleWhileLoading) { setInitial((current) => { if (current !== result) { return result; } return current; }); } }, [result, staleWhileLoading] ); return result; } function cleanEvaluationOptions(options) { const result = {}; for (const [key, value] of Object.entries(options)) { if (value !== void 0) { result[key] = value; } } return result; } function useSsrEvaluation(_, { initial } = {}) { if (initial === void 0) { throw new Error( "The initial value is required for server-side rendering (SSR). For help, see https://croct.help/sdk/react/missing-evaluation-result" ); } return initial; } const useEvaluation = isSsr() ? useSsrEvaluation : useCsrEvaluation; export { useEvaluation };