import { AxiosRequestConfig } from 'axios'; import { useCallback, useState } from 'react'; import api from '../lib/api'; import handleAPIError from '../lib/handleAPIError'; type ActiveFetchSetter = (data: ResData) => void; type ActiveFetcher = ( url?: string, config?: AxiosRequestConfig, ) => void; type ActiveFetchHookResponse = { fetch: ActiveFetcher; loading: boolean; }; const useActiveFetch = ( options: { config?: AxiosRequestConfig; onData?: ActiveFetchSetter; onError?: (emsg: Message) => void; url?: string; } = {}, ): ActiveFetchHookResponse => { const { config: baseConfig, onError, onData, url: urlPrefix = '' } = options; const [loading, setLoading] = useState(false); const fetch = useCallback>( (urlPostfix = '', config) => { const url = `${urlPrefix}${urlPostfix}`; if (!url) return; setLoading(true); api .get(url, { ...baseConfig, ...config }) .then(({ data }) => { onData?.call(null, data); }) .catch((error) => { const emsg = handleAPIError(error); onError?.call(null, emsg); }) .finally(() => { setLoading(false); }); }, [urlPrefix, baseConfig, onData, onError], ); return { fetch, loading }; }; export default useActiveFetch;