@selfcommunity/react-core
Version:
React Core Components useful for integrating UI Community components (react-ui).
60 lines (59 loc) • 2.17 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
/**
:::info
This custom hook manages cached data and the loading state.
:::
*/
function useSCCachingManager() {
// Elements(id) already loaded
const cache = (0, react_1.useRef)([]);
// Elements(id) current in loading
const loadingCache = (0, react_1.useRef)([]);
// Trigger state changes
const [loading, setDataLoading] = (0, react_1.useState)([]);
const [data, setData] = (0, react_1.useState)([]);
/**
* Update cache
* @param ids
*/
const updateCache = (0, react_1.useMemo)(() => (ids) => {
ids.map((c) => {
if (!cache.current.includes(c)) {
cache.current.push(c);
}
});
}, [cache]);
/**
* Empty cache
* emptying the cache each isFollow request
* results in a request to the server
*/
const emptyCache = (0, react_1.useMemo)(() => () => {
cache.current = [];
loadingCache.current = [];
}, [cache]);
/**
* Category is checking
* Return true if the manager is checking
* the follow status of the obj
* @param category
*/
const isLoading = (0, react_1.useMemo)(() => (v) => {
if (typeof v === 'number') {
return loadingCache.current.includes(v);
}
return loadingCache.current.includes(v.id);
}, [loading, loadingCache]);
const setLoading = (0, react_1.useMemo)(() => (id) => {
loadingCache.current = loadingCache.current.includes(id) ? loadingCache.current : [...loadingCache.current, ...[id]];
setDataLoading((prev) => (prev.includes(id) ? prev : [...prev, ...[id]]));
}, [loadingCache, loading]);
const setUnLoading = (0, react_1.useMemo)(() => (id) => {
loadingCache.current = loadingCache.current.filter((u) => u !== id);
setDataLoading((prev) => prev.filter((u) => u !== id));
}, [loadingCache, loading]);
return { cache: cache.current, updateCache, emptyCache, data, setData, loading, setLoading, setUnLoading, isLoading };
}
exports.default = useSCCachingManager;
;