fetch-react-hook
Version:
Performant, flexible and extensible fetch library for React Hooks
76 lines (70 loc) • 2.54 kB
text/typescript
import { FC, ReactNode } from 'react';
type IStatus = "success" | "loading" | "error";
type OnFinishType<R, I> = {
status: "error" | "success";
response?: R;
payload: I;
};
type OnErrorType = {
message?: string;
};
type UseFetchProps<D, I, R> = {
autoFetch?: boolean;
enableLoading?: boolean;
initialData?: D;
onSuccess?: (res: R, payload: I) => void;
defaultParams?: Partial<I>;
beforeAutoFetch?: () => Partial<I> | undefined;
onError?: (error: OnErrorType, payload: I) => void;
onFinish?: (message: string, options: OnFinishType<R, I>) => void;
setMessage?: (res: R) => string;
onDataSetter?: (data: R) => D;
defaultStatus?: IStatus;
catchKey?: string;
onCache?: (data: D) => void;
justCache?: boolean;
cacheStrategy?: ICacheStrategy;
};
type Fetcher<I, R, O> = (data: I, option?: O) => Promise<R>;
type ResponseFetcher<R> = {
status: "error" | "success";
response?: R;
message?: string;
};
type UseFetch<D, I, R, O> = {
isPending: boolean;
isError: boolean;
data: D;
reFetch: (data?: Partial<I>, configs?: Options<O>) => Promise<ResponseFetcher<R> | never>;
status: IStatus;
setData: (data: D) => void;
};
interface Options<O> {
keepDefaultParams?: boolean;
requestOptions?: O;
}
interface ICacheStrategy {
setItem: <T extends unknown>(key: string, data: T) => void;
getItem: <T extends unknown>(key: string) => T;
removeItem: (key: string) => boolean;
clear: () => void;
}
declare const useFetch: <D, I extends unknown, R, O>(fetcher: Fetcher<I, R, O>, { autoFetch, enableLoading, initialData, onSuccess, defaultParams, beforeAutoFetch, onError, onFinish, setMessage, onDataSetter, defaultStatus, catchKey, onCache, justCache, cacheStrategy, }?: UseFetchProps<D, I, R>) => UseFetch<D, I, R, O>;
type Props = {
children: ReactNode;
cacheStrategy?: ICacheStrategy;
};
declare const FetchProvider: FC<Props>;
declare class MemoryCacheStrategy implements ICacheStrategy {
setItem<T extends unknown>(key: string, data: T): void;
getItem<T extends unknown>(key: string): T;
removeItem(key: string): boolean;
clear(): void;
}
declare class LocalStorageCacheStrategy implements ICacheStrategy {
setItem<T extends unknown>(key: string, data: T): void;
getItem<T extends unknown>(key: string): T;
removeItem(key: string): boolean;
clear(): void;
}
export { FetchProvider, ICacheStrategy, IStatus, LocalStorageCacheStrategy, MemoryCacheStrategy, useFetch as default };