import { useMemo } from 'react'; import useSWR, { BareFetcher, KeyedMutator, SWRConfiguration } from 'swr'; import API_BASE_URL from '../lib/consts/API_BASE_URL'; import fetchJSON from '../lib/fetchers/fetchJSON'; type FetchHookResponse = { data?: D; error?: E; mutate: KeyedMutator; loading: boolean; }; const useFetch = ( url: string, options: SWRConfiguration & { baseUrl?: string; fetcher?: BareFetcher; mod?: (data: Data) => Alt; } = {}, ): FetchHookResponse & { altData?: Alt } => { const { baseUrl = API_BASE_URL, fetcher = fetchJSON, mod, ...config } = options; const { data, error, mutate } = useSWR( `${baseUrl}${url}`, fetcher, config, ); const altData = useMemo( () => mod && data && mod(data), [data, mod], ); const loading = !error && !data; return { altData, data, error, mutate, loading }; }; export default useFetch;