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.

37 lines (36 loc) 1.8 kB
import { FetchError } from "./types/FetchError"; export type UsePostOptions<Response> = { onResponse?: (res: Response) => void; onErrorResponse?: (error: FetchError) => void; onRequestDone?: (url: string, endpoint: string, responseCode: number | string | undefined) => void; convertToFormData?: boolean; removeIfValueIsNullOrUndefined?: boolean; headers?: Record<string, string>; }; /** * A custom React hook for making POST requests using the Fetch API. * @template PostDataType The type of the data to post. * @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). * @param options Optional configuration for the POST request. * @param options.onResponse Callback invoked with the response data on success. * @param options.onErrorResponse Callback invoked with a FetchError on failure. * @param options.convertToFormData If true, converts the payload to FormData. * @param options.removeIfValueIsNullOrUndefined If true, removes null/undefined values from the payload. * @param options.headers Custom headers for the request. * @returns An object containing the error, loading state, and a postData function. * @throws {FetchError} If the request fails or is not aborted. * @example * const { error, loading, postData } = usePost<{ name: string }, { id: string }>( * "http://localhost:5000", * "/api/create", * { convertToFormData: false } * ); * postData({ name: "Item" }); */ export declare function usePost<PostDataType, ResponseType>(baseApiUrl: string, url: string, options?: UsePostOptions<ResponseType>): { error: FetchError | null; loading: boolean; postData: (dataToPost: PostDataType) => Promise<any>; };