UNPKG

@selfcommunity/react-core

Version:

React Core Components useful for integrating UI Community components (react-ui).

79 lines (76 loc) 3.04 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const react_1 = require("react"); const Errors_1 = require("../constants/Errors"); const api_services_1 = require("@selfcommunity/api-services"); const utils_1 = require("@selfcommunity/utils"); const Cache_1 = require("../constants/Cache"); const init = { categories: [], isLoading: true }; // HYDRATE the cache const hydrate = (ids, endpointQueryParams) => { if (!ids) { return null; } const categories = ids.map((id) => { const __categoryCacheKey = (0, Cache_1.getCategoryObjectCacheKey)(id); return utils_1.LRUCache.get(__categoryCacheKey); }); if (categories.filter((c) => !c).length > 0) { // REVALIDATE CACHE return null; } if (endpointQueryParams === null || endpointQueryParams === void 0 ? void 0 : endpointQueryParams.can_create_content) { return categories.filter((c) => !c.content_only_staff); } return categories; }; /** :::info This custom hook is used to fetch categories. :::tip Context can be consumed in this way: ```jsx const {categories, isLoading} = useSCFetchCategories(); ``` ::: * @param props */ const useSCFetchCategories = (props) => { // PROPS const { cacheStrategy = utils_1.CacheStrategies.CACHE_FIRST, endpointQueryParams = {} } = props || {}; // CACHE const __categoriesCacheKey = (0, Cache_1.getCategoriesObjectCacheKey)(); // STATE const categories = cacheStrategy !== utils_1.CacheStrategies.NETWORK_ONLY ? hydrate(utils_1.LRUCache.get(__categoriesCacheKey, null), endpointQueryParams) : null; const [data, setData] = (0, react_1.useState)(categories !== null ? { categories, isLoading: false } : init); /** * Fetch categories */ const fetchCategories = (next = api_services_1.Endpoints.CategoryList.url()) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { const data = yield api_services_1.CategoryService.getAllCategories(Object.assign({ active: true }, endpointQueryParams), { url: next }); return data.next ? data.results.concat(yield fetchCategories(data.next)) : data.results; }); /** * Get categories */ (0, react_1.useEffect)(() => { if (cacheStrategy === utils_1.CacheStrategies.CACHE_FIRST && categories) { return; } fetchCategories() .then((data) => { setData({ categories: data, isLoading: false }); utils_1.LRUCache.set(__categoriesCacheKey, data.map((cat) => { const __categoryCacheKey = (0, Cache_1.getCategoryObjectCacheKey)(cat.id); utils_1.LRUCache.set(__categoryCacheKey, cat); return cat.id; })); }) .catch((error) => { console.log(error); utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, 'Unable to retrieve categories'); }); }, []); return data; }; exports.default = useSCFetchCategories;