UNPKG

@croct/plug-react

Version:

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

87 lines (86 loc) 2.82 kB
"use strict"; "use client"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var useEvaluation_exports = {}; __export(useEvaluation_exports, { useEvaluation: () => useEvaluation }); module.exports = __toCommonJS(useEvaluation_exports); var import_react = require("react"); var import_useLoader = require('./useLoader.cjs'); var import_useCroct = require('./useCroct.cjs'); var import_ssr_polyfills = require('../ssr-polyfills.cjs'); var import_hash = require('../hash.cjs'); function useCsrEvaluation(query, options = {}) { const { cacheKey, fallback, expiration, staleWhileLoading = false, initial: initialValue, ...evaluationOptions } = options; const [initial, setInitial] = (0, import_react.useState)(initialValue); const croct = (0, import_useCroct.useCroct)(); const result = (0, import_useLoader.useLoader)({ cacheKey: (0, import_hash.hash)( `useEvaluation:${cacheKey ?? ""}:${query}:${JSON.stringify(options.attributes ?? {})}` ), loader: () => croct.evaluate(query, cleanEvaluationOptions(evaluationOptions)), initial, fallback, expiration }); (0, import_react.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 = (0, import_ssr_polyfills.isSsr)() ? useSsrEvaluation : useCsrEvaluation; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { useEvaluation });