fix(striker-ui): correct generics in active fetch hook

main
Tsu-ba-me 11 months ago
parent d1bb8df8f2
commit 7e43104a35
  1. 29
      striker-ui/hooks/useActiveFetch.ts

@ -1,30 +1,35 @@
import { AxiosRequestConfig } from 'axios';
import { useCallback, useState } from 'react'; import { useCallback, useState } from 'react';
import api from '../lib/api'; import api from '../lib/api';
import handleAPIError from '../lib/handleAPIError'; import handleAPIError from '../lib/handleAPIError';
type ActiveFetchSetter<T> = (data: T) => void; type ActiveFetchSetter<ResData> = (data: ResData) => void;
type ActiveFetcher = (url?: string) => void; type ActiveFetcher<ReqData> = (
url?: string,
config?: AxiosRequestConfig<ReqData>,
) => void;
type ActiveFetchHookResponse = { type ActiveFetchHookResponse<ReqData> = {
fetch: ActiveFetcher; fetch: ActiveFetcher<ReqData>;
loading: boolean; loading: boolean;
}; };
const useActiveFetch = <Data>( const useActiveFetch = <ResData, ReqData = unknown>(
options: { options: {
onData?: ActiveFetchSetter<Data>; config?: AxiosRequestConfig<ReqData>;
onData?: ActiveFetchSetter<ResData>;
onError?: (emsg: Message) => void; onError?: (emsg: Message) => void;
url?: string; url?: string;
} = {}, } = {},
): ActiveFetchHookResponse => { ): ActiveFetchHookResponse<ReqData> => {
const { onError, onData, url: urlPrefix = '' } = options; const { config: baseConfig, onError, onData, url: urlPrefix = '' } = options;
const [loading, setLoading] = useState<boolean>(false); const [loading, setLoading] = useState<boolean>(false);
const fetch = useCallback<ActiveFetcher>( const fetch = useCallback<ActiveFetcher<ReqData>>(
(urlPostfix = '') => { (urlPostfix = '', config) => {
const url = `${urlPrefix}${urlPostfix}`; const url = `${urlPrefix}${urlPostfix}`;
if (!url) return; if (!url) return;
@ -32,7 +37,7 @@ const useActiveFetch = <Data>(
setLoading(true); setLoading(true);
api api
.get<Data>(url) .get<ResData>(url, { ...baseConfig, ...config })
.then(({ data }) => { .then(({ data }) => {
onData?.call(null, data); onData?.call(null, data);
}) })
@ -45,7 +50,7 @@ const useActiveFetch = <Data>(
setLoading(false); setLoading(false);
}); });
}, },
[urlPrefix, setLoading, onError, onData], [urlPrefix, baseConfig, onData, onError],
); );
return { fetch, loading }; return { fetch, loading };

Loading…
Cancel
Save