UNPKG

@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.

32 lines (31 loc) 1.49 kB
import { FetchError } from "./types/FetchError"; export type UseDeleteOptions<Response> = { onResponse?: (res: Response) => void; onErrorResponse?: (error: FetchError) => void; onRequestDone?: (url: string, endpoint: string, responseCode: number | string | undefined) => void; headers?: Record<string, string>; }; /** * A custom React hook for making DELETE requests using the Fetch API. * @template ResponseType The type of the response data. * @param baseApiUrl The base URL for the API (e.g., "http://localhost:5000"). * @param url The API endpoint URL (relative, without the ID). * @param options Optional configuration for the DELETE request. * @param options.onResponse Callback invoked with the response data on success. * @param options.onErrorResponse Callback invoked with a FetchError on failure. * @param options.headers Custom headers for the request. * @returns An object containing the error, loading state, and a deleteData function. * @throws {FetchError} If the request fails or is not aborted. * @example * const { error, loading, deleteData } = useDelete<{ message: string }>( * "http://localhost:5000", * "/api/delete", * { headers: { Authorization: "Bearer token" } } * ); * deleteData(123); */ export declare function useDelete<ResponseType>(baseApiUrl: string, url: string, options?: UseDeleteOptions<ResponseType>): { error: FetchError | null; loading: boolean; deleteData: (id: number | string) => Promise<any>; };