UNPKG

@selfcommunity/react-core

Version:

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

73 lines (72 loc) 3.07 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"); /** :::info This custom hooks is used to fetch a course lesson comment. ::: * @param object * @param object.id * @param object.commentObject * @param object.lesson * @param object.cacheStrategy */ function useSCFetchLessonCommentObject({ id = null, commentObject = null, lesson = null, cacheStrategy = utils_1.CacheStrategies.CACHE_FIRST, }) { const __commentObjectId = commentObject ? commentObject.id : id; // CACHE const __commentObjectCacheKey = (0, Cache_1.getLessonCommentCacheKey)(__commentObjectId); const [obj, setObj] = (0, react_1.useState)(cacheStrategy !== utils_1.CacheStrategies.NETWORK_ONLY ? utils_1.LRUCache.get(__commentObjectCacheKey, commentObject) : commentObject); const [error, setError] = (0, react_1.useState)(null); /** * Memoized fetchLessonCommentObject */ const fetchLessonCommentObject = (0, react_1.useMemo)(() => () => { return api_services_1.http .request({ url: api_services_1.Endpoints.GetCourseLessonComment.url({ id: lesson.course_id, section_id: lesson.section_id, lesson_id: lesson.id, comment_id: __commentObjectId, }), method: api_services_1.Endpoints.GetCourseLessonComment.method, }) .then((res) => { if (res.status >= 300) { return Promise.reject(res); } return Promise.resolve(res.data); }); }, [__commentObjectId, lesson]); /** * If course commentObject resolve it */ (0, react_1.useEffect)(() => { if (__commentObjectId && lesson && (!obj || cacheStrategy === utils_1.CacheStrategies.STALE_WHILE_REVALIDATE)) { fetchLessonCommentObject() .then((obj) => { setObj(obj); utils_1.LRUCache.set(__commentObjectCacheKey, obj); }) .catch((err) => { utils_1.LRUCache.delete(__commentObjectCacheKey); setError(`Course Lesson comment Object with id ${id} not found`); utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, `Course Lesson comment Object with id ${id} not found`); utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, err.message); }); } }, [__commentObjectId, lesson]); (0, use_deep_compare_effect_1.useDeepCompareEffectNoCheck)(() => { if (commentObject) { setObj(commentObject); utils_1.LRUCache.set(__commentObjectCacheKey, obj); } }, [commentObject]); return { obj, setObj, error }; } exports.default = useSCFetchLessonCommentObject;