@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.82 kB
TypeScript
import { FetchError } from "./types/FetchError";
export type UsePutOptions<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 PUT requests using the Fetch API.
* @template PutDataType The type of the data to put.
* @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 PUT 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 putData function.
* @throws {FetchError} If the request fails or is not aborted.
* @example
* const { error, loading, putData } = usePut<{ id: string, name: string }, { message: string }>(
* "http://localhost:5000",
* "/api/update",
* { convertToFormData: false }
* );
* putData({ id: "123", name: "Updated" });
*/
export declare function usePut<PutDataType, ResponseType>(baseApiUrl: string, url: string, options?: UsePutOptions<ResponseType>): {
error: FetchError | null;
loading: boolean;
putData: (dataToPut: PutDataType) => Promise<any>;
};