create-fetch-hooks
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.63 kB
JavaScript
import { useState } from "react";
import { removeMultipleSlashes } from "./utils/removeMultipleSlashes";
import { del } from "./del";
export function useDelete(baseApiUrl, url, options) {
const [error, setError] = useState();
const [deleting, setLoading] = useState(false);
const cleanUrl = removeMultipleSlashes(`${baseApiUrl}/${url}`);
async function deleteData(id) {
setLoading(true);
del(baseApiUrl, `${url}/${id || ""}`, {
headers: options === null || options === void 0 ? void 0 : options.headers,
onSuccess(res) {
var _a;
(_a = options === null || options === void 0 ? void 0 : options.onSuccess) === null || _a === void 0 ? void 0 : _a.call(options, res);
},
onError(error) {
var _a;
setError(error);
(_a = options === null || options === void 0 ? void 0 : options.onError) === null || _a === void 0 ? void 0 : _a.call(options, error);
},
onResponseGot(url, endpoint, responseCode) {
var _a;
setLoading(false);
(_a = options === null || options === void 0 ? void 0 : options.onResponseGot) === null || _a === void 0 ? void 0 : _a.call(options, url, endpoint, responseCode);
},
accessTokenLocalStorageKey: options === null || options === void 0 ? void 0 : options.accessTokenLocalStorageKey,
callRefreshToken: options === null || options === void 0 ? void 0 : options.callRefreshToken,
});
}
return { error, loading: deleting, deleteData };
}