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.76 kB
JavaScript
import { useState } from "react";
import { post } from "./post";
export function usePost(baseApiUrl, url, options) {
const [error, setError] = useState();
const [posting, setLoading] = useState(false);
async function postData(dataToPost, id) {
setLoading(true);
post(baseApiUrl, `${url}/${id || ""}`, dataToPost, {
convertToFormData: options === null || options === void 0 ? void 0 : options.convertToFormData,
headers: options === null || options === void 0 ? void 0 : options.headers,
removeIfValueIsNullOrUndefined: options === null || options === void 0 ? void 0 : options.removeIfValueIsNullOrUndefined,
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: posting, postData };
}