import type {ConfigInterface, keyInterface, responseInterface} from 'swr'; import {useEffect, useMemo} from 'react'; import ee from '~/utils/event'; import type {fetcherFn} from 'swr/dist/types'; import {toast} from 'react-toastify'; import useSWR from 'swr'; type Response = responseInterface & { loading: boolean; }; function useRequest(key: keyInterface): Response; function useRequest(key: keyInterface, fetcher?: fetcherFn): Response; function useRequest( key: keyInterface, fetcher?: fetcherFn, config?: ConfigInterface> ): Response; function useRequest( key: keyInterface, fetcher?: fetcherFn, config?: ConfigInterface> ): Response { const {data, error, ...other} = useSWR(key, fetcher, config); const loading = useMemo(() => !!key && data === void 0 && !error, [key, data, error]); useEffect(() => { if (error) { toast(error.message, { position: toast.POSITION.TOP_CENTER, type: toast.TYPE.ERROR }); } }, [error]); return {data, error, loading, ...other}; } function useRunningRequest(key: keyInterface, running: boolean): Response; function useRunningRequest( key: keyInterface, running: boolean, fetcher?: fetcherFn ): Response; function useRunningRequest( key: keyInterface, running: boolean, fetcher?: fetcherFn, config?: Omit>, 'dedupingInterval' | 'errorRetryInterval'> ): Response; function useRunningRequest( key: keyInterface, running: boolean, fetcher?: fetcherFn, config?: Omit>, 'dedupingInterval' | 'errorRetryInterval'> ) { const c = useMemo>>( () => ({ ...config, refreshInterval: running ? config?.refreshInterval ?? 15 * 1000 : 0, dedupingInterval: config?.refreshInterval ?? 15 * 1000, errorRetryInterval: config?.refreshInterval ?? 15 * 1000 }), [running, config] ); const {mutate, ...others} = useRequest(key, fetcher, c); // revalidate immediately when running is set to true useEffect(() => { if (running) { mutate(); } }, [running, mutate]); useEffect(() => { ee.on('refresh', mutate); return () => { ee.off('refresh', mutate); }; }, [mutate]); return {mutate, ...others}; } export default useRequest; export {useRunningRequest};