@croct/plug-react
Version:
React components and hooks to plug your React applications into Croct.
83 lines (82 loc) • 2.59 kB
JavaScript
;
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 useLoader_exports = {};
__export(useLoader_exports, {
useLoader: () => useLoader
});
module.exports = __toCommonJS(useLoader_exports);
var import_react = require("react");
var import_Cache = require('./Cache.cjs');
const cache = new import_Cache.Cache(60 * 1e3);
function useLoader({ initial, ...currentOptions }) {
const optionsRef = (0, import_react.useRef)(currentOptions);
const [value, setValue] = (0, import_react.useState)(() => cache.get(currentOptions.cacheKey)?.result ?? initial);
const mountedRef = (0, import_react.useRef)(true);
const load = (0, import_react.useCallback)(
(options) => {
try {
setValue(cache.load(options));
} catch (result) {
if (result instanceof Promise) {
void result.then((resolvedValue) => {
if (mountedRef.current) {
setValue(resolvedValue);
}
});
return;
}
setValue(void 0);
}
},
[]
);
(0, import_react.useEffect)(
() => {
mountedRef.current = true;
if (initial !== void 0) {
load(currentOptions);
}
return () => {
mountedRef.current = false;
};
},
// eslint-disable-next-line react-hooks/exhaustive-deps -- Should run only once
[]
);
(0, import_react.useEffect)(
() => {
if (optionsRef.current.cacheKey !== currentOptions.cacheKey) {
setValue(initial);
optionsRef.current = currentOptions;
if (initial !== void 0) {
load(currentOptions);
}
}
},
[currentOptions, initial, load]
);
if (value === void 0) {
return cache.load(currentOptions);
}
return value;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
useLoader
});