UNPKG

@selfcommunity/react-core

Version:

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

74 lines (73 loc) 3.24 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 an incubator object. ::: * @param object * @param object.id * @param object.incubator * @param object.cacheStrategy */ function useSCFetchIncubator({ id = null, incubator = null, cacheStrategy = utils_1.CacheStrategies.CACHE_FIRST, }) { const __incubatorId = incubator ? incubator.id : id; // CONTEXT const scUserContext = (0, SCUserProvider_1.useSCUser)(); const authUserId = scUserContext.user ? scUserContext.user.id : null; // CACHE const __incubatorCacheKey = (0, Cache_1.getIncubatorObjectCacheKey)(__incubatorId); const __incubator = authUserId ? incubator : (0, utils_1.objectWithoutProperties)(incubator, ['subscribed']); const [scIncubator, setSCIncubator] = (0, react_1.useState)(cacheStrategy !== utils_1.CacheStrategies.NETWORK_ONLY ? utils_1.LRUCache.get(__incubatorCacheKey, __incubator) : null); const [error, setError] = (0, react_1.useState)(null); /** * Memoized fetchIncubator */ const fetchIncubator = (0, react_1.useMemo)(() => () => { return api_services_1.http .request({ url: api_services_1.Endpoints.GetASpecificIncubator.url({ id: __incubatorId }), method: api_services_1.Endpoints.GetASpecificIncubator.method, }) .then((res) => { if (res.status >= 300) { return Promise.reject(res); } return Promise.resolve(res.data); }); }, [__incubatorId]); /** * If id resolve the obj */ (0, react_1.useEffect)(() => { if (__incubatorId && (!scIncubator || (scIncubator && __incubatorId !== scIncubator.id))) { fetchIncubator() .then((obj) => { const _i = authUserId ? obj : (0, utils_1.objectWithoutProperties)(obj, ['subscribed']); setSCIncubator(_i); utils_1.LRUCache.set(__incubatorCacheKey, _i); }) .catch((err) => { utils_1.LRUCache.delete(__incubatorCacheKey); setError(`Incubator with id ${id} not found`); utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, `Incubator with id ${id} not found`); utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, err.message); }); } }, [__incubatorId]); (0, use_deep_compare_effect_1.useDeepCompareEffectNoCheck)(() => { if (incubator) { const _i = authUserId ? incubator : (0, utils_1.objectWithoutProperties)(incubator, ['subscribed']); setSCIncubator(_i); utils_1.LRUCache.set(__incubatorCacheKey, _i); } }, [incubator]); return { scIncubator, setSCIncubator, error }; } exports.default = useSCFetchIncubator;