UNPKG

@selfcommunity/react-core

Version:

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

68 lines (67 loc) 2.81 kB
import { Endpoints, http } from '@selfcommunity/api-services'; import { CacheStrategies, Logger, LRUCache } from '@selfcommunity/utils'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { useDeepCompareEffectNoCheck } from 'use-deep-compare-effect'; import { useSCUser } from '../components/provider/SCUserProvider'; import { getPaymentOrderObjectCacheKey } from '../constants/Cache'; import { SCOPE_SC_CORE } from '../constants/Errors'; /** :::info This custom hook is used to fetch a payment order. ::: * @param object * @param object.id * @param object.paymentOrder * @param object.cacheStrategy */ export default function useSCFetchPaymentOrder({ id = null, paymentOrder = null, cacheStrategy = CacheStrategies.NETWORK_ONLY, }) { const __paymentOrderId = useMemo(() => (paymentOrder === null || paymentOrder === void 0 ? void 0 : paymentOrder.id) || id, [paymentOrder, 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 __paymentOrderCacheKey = useMemo(() => getPaymentOrderObjectCacheKey(__paymentOrderId), [__paymentOrderId]); const [scPaymentOrder, setScPaymentOrder] = useState(cacheStrategy !== CacheStrategies.NETWORK_ONLY ? LRUCache.get(__paymentOrderCacheKey, paymentOrder) : null); const [error, setError] = useState(null); const setSCPaymentOrder = useCallback((c) => { setScPaymentOrder(c); LRUCache.set(__paymentOrderCacheKey, c); }, [setScPaymentOrder, __paymentOrderCacheKey]); /** * Memoized fetch order */ const fetchPaymentOrder = useMemo(() => (id) => { return http .request({ url: Endpoints.GetPaymentOrder.url({ id }), method: Endpoints.GetPaymentOrder.method, }) .then((res) => { if (res.status >= 300) { return Promise.reject(res); } return Promise.resolve(res.data); }); }, []); /** * If id attempt to get the course by id */ useEffect(() => { if (id !== null && id !== undefined && !paymentOrder) { fetchPaymentOrder(id) .then((e) => { setSCPaymentOrder(e); }) .catch((err) => { LRUCache.delete(__paymentOrderCacheKey); Logger.error(SCOPE_SC_CORE, err.message); }); } }, [id, paymentOrder, authUserId]); useDeepCompareEffectNoCheck(() => { if (paymentOrder) { setSCPaymentOrder(paymentOrder); } }, [paymentOrder, authUserId]); return { scPaymentOrder, setSCPaymentOrder, error }; }