fix(striker-ui): add mod option to fetch hook

main
Tsu-ba-me 11 months ago
parent cc10eab7f3
commit b2c933ac1e
  1. 22
      striker-ui/hooks/useFetch.tsx

@ -1,3 +1,4 @@
import { useMemo } from 'react';
import useSWR, { BareFetcher, SWRConfiguration } from 'swr'; import useSWR, { BareFetcher, SWRConfiguration } from 'swr';
import API_BASE_URL from '../lib/consts/API_BASE_URL'; import API_BASE_URL from '../lib/consts/API_BASE_URL';
@ -10,20 +11,31 @@ type FetchHookResponse<D, E extends Error = Error> = {
loading: boolean; loading: boolean;
}; };
const useFetch = <Data,>( const useFetch = <Data, Alt = Data>(
url: string, url: string,
options: SWRConfiguration<Data> & { options: SWRConfiguration<Data> & {
fetcher?: BareFetcher<Data>;
baseUrl?: string; baseUrl?: string;
fetcher?: BareFetcher<Data>;
mod?: (data: Data) => Alt;
} = {}, } = {},
): FetchHookResponse<Data> => { ): FetchHookResponse<Data> & { altData?: Alt } => {
const { fetcher = fetchJSON, baseUrl = API_BASE_URL, ...config } = options; const {
baseUrl = API_BASE_URL,
fetcher = fetchJSON,
mod,
...config
} = options;
const { data, error } = useSWR<Data>(`${baseUrl}${url}`, fetcher, config); const { data, error } = useSWR<Data>(`${baseUrl}${url}`, fetcher, config);
const altData = useMemo<Alt | undefined>(
() => mod && data && mod(data),
[data, mod],
);
const loading = !error && !data; const loading = !error && !data;
return { data, error, loading }; return { altData, data, error, loading };
}; };
export default useFetch; export default useFetch;

Loading…
Cancel
Save