UNPKG

@selfcommunity/react-core

Version:

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

74 lines (73 loc) 2.89 kB
import { Endpoints, http } from '@selfcommunity/api-services'; import { CacheStrategies, Logger, LRUCache, objectWithoutProperties } from '@selfcommunity/utils'; import { useEffect, useMemo, useState } from 'react'; import { useDeepCompareEffectNoCheck } from 'use-deep-compare-effect'; import { useSCUser } from '../components/provider/SCUserProvider'; import { getLiveStreamObjectCacheKey } from '../constants/Cache'; import { SCOPE_SC_CORE } from '../constants/Errors'; /** :::info This custom hook is used to fetch an liveStream object. ::: * @param object * @param object.id * @param object.liveStream * @param object.cacheStrategy */ export default function useSCFetchLiveStream({ id = null, liveStream = null, cacheStrategy = CacheStrategies.CACHE_FIRST, }) { const __eventId = liveStream ? liveStream.id : id; // CONTEXT const scUserContext = useSCUser(); const authUserId = scUserContext.user ? scUserContext.user.id : null; // CACHE const __liveStreamCacheKey = getLiveStreamObjectCacheKey(__eventId); const __liveStream = authUserId ? liveStream : objectWithoutProperties(liveStream, ['subscription_status']); const [scLiveStream, setScLiveStream] = useState(cacheStrategy !== CacheStrategies.NETWORK_ONLY ? LRUCache.get(__liveStreamCacheKey, __liveStream) : null); const [error, setError] = useState(null); /** * Memoized setSCLiveStream (auto-subscription if need it) */ const setSCLiveStream = useMemo(() => (e) => { setScLiveStream(e); LRUCache.set(__liveStreamCacheKey, e); }, [authUserId, setScLiveStream]); /** * Memoized fetchTag */ const fetchLiveStream = useMemo(() => (id) => { return http .request({ url: Endpoints.GetLiveStreamInfo.url({ id }), method: Endpoints.GetLiveStreamInfo.method, }) .then((res) => { if (res.status >= 300) { return Promise.reject(res); } return Promise.resolve(res.data); }); }, []); /** * If id attempt to get the liveStream by id */ useEffect(() => { if (id !== null && id !== undefined && !liveStream) { fetchLiveStream(id) .then((e) => { setSCLiveStream(e); }) .catch((err) => { LRUCache.delete(__liveStreamCacheKey); setError(`LiveStream with id ${id} not found`); Logger.error(SCOPE_SC_CORE, `LiveStream with id ${id} not found`); Logger.error(SCOPE_SC_CORE, err.message); }); } }, [id, liveStream, authUserId]); useDeepCompareEffectNoCheck(() => { if (liveStream) { setSCLiveStream(liveStream); } }, [liveStream, authUserId]); return { scLiveStream, setSCLiveStream, error }; }