UNPKG

@selfcommunity/react-core

Version:

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

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