UNPKG

@selfcommunity/react-core

Version:

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

70 lines (69 loc) 2.83 kB
import { Endpoints, http } from '@selfcommunity/api-services'; import { CacheStrategies, Logger, LRUCache } from '@selfcommunity/utils'; import { useEffect, useMemo, useState } from 'react'; import { useDeepCompareEffectNoCheck } from 'use-deep-compare-effect'; import { useSCUser } from '../components/provider/SCUserProvider'; import { getLessonObjectCacheKey } from '../constants/Cache'; import { SCOPE_SC_CORE } from '../constants/Errors'; /** :::info This custom hook is used to fetch a lesson object. ::: * @param object * @param object.id * @param object.lesson * @param object.cacheStrategy */ export default function useSCFetchLesson({ id = null, lesson = null, courseId = null, sectionId = null, cacheStrategy = CacheStrategies.CACHE_FIRST, }) { const __lessonId = useMemo(() => (lesson === null || lesson === void 0 ? void 0 : lesson.id) || id, [lesson, id]); // CONTEXT const scUserContext = useSCUser(); const authUserId = useMemo(() => { var _a; return ((_a = scUserContext.user) === null || _a === void 0 ? void 0 : _a.id) || null; }, [scUserContext.user]); // CACHE const __lessonCacheKey = useMemo(() => getLessonObjectCacheKey(__lessonId), [__lessonId]); const [scLesson, setScLesson] = useState(cacheStrategy !== CacheStrategies.NETWORK_ONLY ? LRUCache.get(__lessonCacheKey, lesson) : null); const [error, setError] = useState(null); const setSCLesson = (lesson) => { setScLesson(lesson); LRUCache.set(__lessonCacheKey, lesson); }; /** * Memoized fetchTag */ const fetchLesson = useMemo(() => (id) => { return http .request({ url: Endpoints.GetCourseLesson.url({ id: courseId, section_id: sectionId, lesson_id: id }), method: Endpoints.GetCourseLesson.method, }) .then((res) => { if (res.status >= 300) { return Promise.reject(res); } return Promise.resolve(res.data); }); }, [courseId, sectionId, id]); /** * If id attempt to get the lesson by id */ useEffect(() => { if (__lessonId && courseId && sectionId) { fetchLesson(__lessonId) .then((e) => { setSCLesson(e); }) .catch((err) => { LRUCache.delete(__lessonCacheKey); setError(`Lesson with id ${__lessonId} not found`); Logger.error(SCOPE_SC_CORE, `Lesson with id ${__lessonId} not found`); Logger.error(SCOPE_SC_CORE, err.message); }); } }, [__lessonId, courseId, sectionId]); useDeepCompareEffectNoCheck(() => { if (lesson) { setSCLesson(lesson); } }, [lesson, authUserId]); return { scLesson, setSCLesson, error }; }