diff --git a/striker-ui/hooks/useFetch.tsx b/striker-ui/hooks/useFetch.tsx new file mode 100644 index 00000000..bbe77894 --- /dev/null +++ b/striker-ui/hooks/useFetch.tsx @@ -0,0 +1,29 @@ +import useSWR, { BareFetcher, 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; + loading: boolean; +}; + +const useFetch = ( + url: string, + options: SWRConfiguration & { + fetcher?: BareFetcher; + baseUrl?: string; + } = {}, +): FetchHookResponse => { + const { fetcher = fetchJSON, baseUrl = API_BASE_URL, ...config } = options; + + const { data, error } = useSWR(`${baseUrl}${url}`, fetcher, config); + + const loading = !error && !data; + + return { data, error, loading }; +}; + +export default useFetch;