@croct/plug-react
Version:
React components and hooks to plug your React applications into Croct.
59 lines (58 loc) • 1.47 kB
JavaScript
import { useCallback, useEffect, useRef, useState } from "react";
import { Cache } from "./Cache.js";
const cache = new Cache(60 * 1e3);
function useLoader({ initial, ...currentOptions }) {
const optionsRef = useRef(currentOptions);
const [value, setValue] = useState(() => cache.get(currentOptions.cacheKey)?.result ?? initial);
const mountedRef = useRef(true);
const load = useCallback(
(options) => {
try {
setValue(cache.load(options));
} catch (result) {
if (result instanceof Promise) {
result.then((resolvedValue) => {
if (mountedRef.current) {
setValue(resolvedValue);
}
});
return;
}
setValue(void 0);
}
},
[]
);
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
[]
);
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;
}
export {
useLoader
};