@ashraflabs/use-api
Version:
A simple and powerful custom React hook (useApi) that simplifies API requests with automatic loading and error states. Ideal for clean and maintainable data fetching in React components.
41 lines (40 loc) • 1.88 kB
TypeScript
import { UseGetOptions } from "./useGet";
import { UsePostOptions } from "./usePost";
import { UsePutOptions } from "./usePut";
import { UseDeleteOptions } from "./useDelete";
/**
* A factory hook that provides a set of API hooks with a shared base API URL.
* @param baseApiUrl The base URL for all API requests (e.g., "http://localhost:5000").
* @returns An object containing useGet, usePost, usePut, and useDelete hooks.
* @example
* const { useGet, usePost, usePut, useDelete } = useApi("http://localhost:5000");
* const { data } = useGet<User>("/api/user");
* const { postData } = usePost<{ name: string }, { id: string }>("/api/create");
*/
export type UseApiOptions = {
headers?: Record<string, string>;
onRequestDone?: (url: string, endpoint: string, responseCode: number | string | undefined) => void;
};
export declare function useApi(baseApiUrl: string, baseOptions?: UseApiOptions): {
useGet: <T>(url: string, options?: UseGetOptions<T>) => {
data: T | undefined;
error: import("./classes").default | undefined;
loading: boolean;
reload: () => void;
};
usePost: <PostDataType, ResponseType>(url: string, options?: UsePostOptions<ResponseType>) => {
error: import("./types/FetchError").FetchError | null;
loading: boolean;
postData: (dataToPost: PostDataType) => Promise<any>;
};
usePut: <PutDataType, ResponseType>(url: string, options?: UsePutOptions<ResponseType>) => {
error: import("./types/FetchError").FetchError | null;
loading: boolean;
putData: (dataToPut: PutDataType) => Promise<any>;
};
useDelete: <ResponseType>(url: string, options?: UseDeleteOptions<ResponseType>) => {
error: import("./types/FetchError").FetchError | null;
loading: boolean;
deleteData: (id: number | string) => Promise<any>;
};
};