UNPKG

@selfcommunity/react-core

Version:

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

84 lines (81 loc) 2.83 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 = { courses: [], isLoading: true }; // HYDRATE the cache const hydrate = (ids) => { if (!ids) { return null; } const courses = ids.map((id) => { const __courseCacheKey = (0, Cache_1.getCourseObjectCacheKey)(id); return utils_1.LRUCache.get(__courseCacheKey); }); if (courses.filter((c) => !c).length > 0) { // REVALIDATE CACHE return null; } return courses; }; /** :::info This custom hook is used to fetch courses. @param object.cacheStrategy :::tip Context can be consumed in this way: ```jsx const {courses, isLoading} = useSCFetchCourses(); ``` ::: * @param props */ const useSCFetchCourses = (props) => { // PROPS const { cacheStrategy = utils_1.CacheStrategies.CACHE_FIRST } = props || {}; // CACHE const __coursesCacheKey = (0, Cache_1.getCoursesObjectCacheKey)(); // STATE const courses = cacheStrategy !== utils_1.CacheStrategies.NETWORK_ONLY ? hydrate(utils_1.LRUCache.get(__coursesCacheKey, null)) : null; const [data, setData] = (0, react_1.useState)(courses !== null ? { courses, isLoading: false } : init); /** * Fetch courses */ const fetchCourses = (next = api_services_1.Endpoints.GetJoinedCourses.url()) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { const response = yield api_services_1.http.request({ url: next, method: api_services_1.Endpoints.GetJoinedCourses.method, }); const data = response.data; if (data.next) { return data.results.concat(yield fetchCourses(data.next)); } return data.results; }); /** * Get courses */ (0, react_1.useEffect)(() => { if (cacheStrategy === utils_1.CacheStrategies.CACHE_FIRST && courses) { return; } fetchCourses() .then((data) => { setData({ courses: data, isLoading: false }); utils_1.LRUCache.set(__coursesCacheKey, data.map((course) => { const __courseCacheKey = (0, Cache_1.getCourseObjectCacheKey)(course.id); utils_1.LRUCache.set(__courseCacheKey, course); return course.id; })); }) .catch((error) => { console.log(error); utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, 'Unable to retrieve courses'); }); }, []); return data; }; exports.default = useSCFetchCourses;