UNPKG

@selfcommunity/react-core

Version:

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

82 lines (81 loc) 3.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = require("react"); const api_services_1 = require("@selfcommunity/api-services"); const utils_1 = require("@selfcommunity/utils"); const Errors_1 = require("../constants/Errors"); const types_1 = require("@selfcommunity/types"); const use_deep_compare_effect_1 = require("use-deep-compare-effect"); const Cache_1 = require("../constants/Cache"); /** :::info This custom hook is used to fetch a feed object. ::: * @param object * @param object.id * @param object.feedObject * @param object.feedObjectType * @param object.cacheStrategy */ function useSCFetchFeedObject({ id = null, feedObject = null, feedObjectType = types_1.SCContributionType.POST || types_1.SCContributionType.DISCUSSION || types_1.SCContributionType.STATUS, cacheStrategy = utils_1.CacheStrategies.CACHE_FIRST, }) { const __feedObjectId = feedObject ? feedObject.id : id; const __feedObjectType = feedObject ? feedObject.type : feedObjectType; // CACHE const __feedObjectCacheKey = (0, Cache_1.getFeedObjectCacheKey)(__feedObjectId, __feedObjectType); const [obj, setObj] = (0, react_1.useState)(cacheStrategy !== utils_1.CacheStrategies.NETWORK_ONLY ? utils_1.LRUCache.get(__feedObjectCacheKey, feedObject) : feedObject); const [error, setError] = (0, react_1.useState)(null); /** * Memoized fetchFeedObject */ const fetchFeedObject = (0, react_1.useMemo)(() => () => { return api_services_1.http .request({ url: api_services_1.Endpoints.FeedObject.url({ type: __feedObjectType, id: __feedObjectId }), method: api_services_1.Endpoints.FeedObject.method, }) .then((res) => { if (res.status >= 300) { return Promise.reject(res); } return Promise.resolve(res.data); }); }, [__feedObjectId, __feedObjectType]); /** * If id and feedObjectType resolve feedObject */ (0, react_1.useEffect)(() => { if (__feedObjectId && __feedObjectType && !feedObject) { fetchFeedObject() .then((obj) => { setObj(obj); utils_1.LRUCache.set(__feedObjectCacheKey, obj); }) .catch((err) => { utils_1.LRUCache.delete(__feedObjectCacheKey); setError(`FeedObject with id ${id} not found`); utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, `FeedObject with id ${id} not found`); utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, err.message); }); } }, [__feedObjectId, __feedObjectType]); (0, use_deep_compare_effect_1.useDeepCompareEffectNoCheck)(() => { if (feedObject) { if (cacheStrategy === utils_1.CacheStrategies.NETWORK_ONLY) { setObj(feedObject); utils_1.LRUCache.set(__feedObjectCacheKey, feedObject); } else { setObj(utils_1.LRUCache.get(__feedObjectCacheKey, feedObject)); } } }, [feedObject]); return { obj, setObj: (newObj) => { utils_1.LRUCache.set(__feedObjectCacheKey, newObj); setObj(Object.assign({}, newObj)); }, error, }; } exports.default = useSCFetchFeedObject;