UNPKG

@selfcommunity/react-core

Version:

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

74 lines (73 loc) 3.18 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 use_deep_compare_effect_1 = require("use-deep-compare-effect"); const SCUserProvider_1 = require("../components/provider/SCUserProvider"); /** :::info This custom hook is used to fetch a category object. ::: * @param object * @param object.id * @param object.category * @param object.cacheStrategy */ function useSCFetchCategory({ id = null, category = null, cacheStrategy = utils_1.CacheStrategies.CACHE_FIRST, }) { const __categoryId = category ? category.id : id; // CONTEXT const scUserContext = (0, SCUserProvider_1.useSCUser)(); const authUserId = scUserContext.user ? scUserContext.user.id : null; // CACHE const __categoryCacheKey = (0, Cache_1.getCategoryObjectCacheKey)(__categoryId); const __category = authUserId ? category : (0, utils_1.objectWithoutProperties)(category, ['followed']); const [scCategory, setSCCategory] = (0, react_1.useState)(cacheStrategy !== utils_1.CacheStrategies.NETWORK_ONLY ? utils_1.LRUCache.get(__categoryCacheKey, __category) : null); const [error, setError] = (0, react_1.useState)(null); /** * Memoized fetchTag */ const fetchCategory = (0, react_1.useMemo)(() => () => { return api_services_1.http .request({ url: api_services_1.Endpoints.Category.url({ id: __categoryId }), method: api_services_1.Endpoints.Category.method, }) .then((res) => { if (res.status >= 300) { return Promise.reject(res); } return Promise.resolve(res.data); }); }, [__categoryId]); /** * If id attempt to get the category by id */ (0, react_1.useEffect)(() => { if (__categoryId && (!scCategory || (scCategory && __categoryId !== scCategory.id))) { fetchCategory() .then((obj) => { const _c = authUserId ? obj : (0, utils_1.objectWithoutProperties)(obj, ['followed']); setSCCategory(_c); utils_1.LRUCache.set(__categoryCacheKey, _c); }) .catch((err) => { utils_1.LRUCache.delete(__categoryCacheKey); setError(`Category with id ${id} not found`); utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, `Category with id ${id} not found`); utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, err.message); }); } }, [__categoryId]); (0, use_deep_compare_effect_1.useDeepCompareEffectNoCheck)(() => { if (category) { const _c = authUserId ? category : (0, utils_1.objectWithoutProperties)(category, ['followed']); setSCCategory(_c); utils_1.LRUCache.set(__categoryCacheKey, _c); } }, [category]); return { scCategory, setSCCategory, error }; } exports.default = useSCFetchCategory;