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.

70 lines (69 loc) 3.29 kB
import { useState } from "react"; import { FetchError } from "./types/FetchError"; import { removeMultipleSlashes } from "./utils/removeMultipleSlashes"; /** * 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 function useDelete(baseApiUrl, url, options) { const [error, setError] = useState(null); const [loading, setLoading] = useState(false); /** * Sends a DELETE request for the specified resource ID. * @param id The ID of the resource to delete. * @returns A promise resolving to the response data. */ const cleanUrl = removeMultipleSlashes(`${baseApiUrl}/${url}`); async function deleteData(id) { var _a, _b, _c; setLoading(true); const cleanedUrl = removeMultipleSlashes(`${cleanUrl}/${id}`); let responseCode; try { const response = await fetch(cleanedUrl, { method: "DELETE", headers: { ...((options === null || options === void 0 ? void 0 : options.headers) || {}), }, }); responseCode = response.status; if (!response.ok) { throw new FetchError(`HTTP error! Status: ${response.status}`, response, response.status); } const res = await response.json(); setError(null); (_a = options === null || options === void 0 ? void 0 : options.onResponse) === null || _a === void 0 ? void 0 : _a.call(options, res); return res; } catch (err) { if (err instanceof Error && err.name !== "AbortError") { const fetchErr = err instanceof FetchError ? err : new FetchError(err.message); setError(fetchErr); (_b = options === null || options === void 0 ? void 0 : options.onErrorResponse) === null || _b === void 0 ? void 0 : _b.call(options, fetchErr); if (fetchErr.status !== undefined) { responseCode = fetchErr.status || undefined; } } } finally { setLoading(false); (_c = options === null || options === void 0 ? void 0 : options.onRequestDone) === null || _c === void 0 ? void 0 : _c.call(options, cleanUrl, removeMultipleSlashes(cleanUrl.replace(baseApiUrl, "/")).split("?")[0], responseCode); } } return { error, loading, deleteData }; }