UNPKG

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.

70 lines (69 loc) 3.63 kB
import { useCallback, useEffect, useState } from "react"; import { removeMultipleSlashes } from "./utils/removeMultipleSlashes"; import { get } from "./get"; import { useFetchCache } from "./FetchCacheProvider"; export function useGet(baseApiUrl, url, options) { const [data, setData] = useState(); const [error, setError] = useState(); const [loading, setLoading] = useState(true); const [trigger, setTrigger] = useState(0); const cache = useFetchCache(); // ✅ get cache context const reload = useCallback(() => { setTrigger((prev) => prev + 1); }, []); const cleanUrl = removeMultipleSlashes(`${baseApiUrl}/${url}`); useEffect(() => { var _a; if (!url) return; if ((options === null || options === void 0 ? void 0 : options.dontRequestIfUrlIncludeNullOrUndefined) && (cleanUrl.includes("undefined") || cleanUrl.includes("null"))) { return; } const controller = new AbortController(); const debounceDelay = (_a = options === null || options === void 0 ? void 0 : options.debounce) !== null && _a !== void 0 ? _a : 0; const timeout = setTimeout(() => { const fetchData = async () => { if (cache === null || cache === void 0 ? void 0 : cache.has(cleanUrl)) { const cached = cache.get(cleanUrl); setData(cached); // setLoading(false); // options?.onSuccess?.(cached); // return; } setLoading(true); get(baseApiUrl, url, { dontRequestIfUrlIncludeNullOrUndefined: options === null || options === void 0 ? void 0 : options.dontRequestIfUrlIncludeNullOrUndefined, headers: options === null || options === void 0 ? void 0 : options.headers, signal: controller.signal, onSuccess(res) { var _a; setData(res); setError(undefined); (_a = options === null || options === void 0 ? void 0 : options.onSuccess) === null || _a === void 0 ? void 0 : _a.call(options, res); cache === null || cache === void 0 ? void 0 : cache.set(cleanUrl, res); }, onError(err) { var _a; setError(err); setData(undefined); (_a = options === null || options === void 0 ? void 0 : options.onError) === null || _a === void 0 ? void 0 : _a.call(options, err); }, 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, }); }; fetchData(); }, debounceDelay); return () => { controller.abort(); clearTimeout(timeout); }; }, [cleanUrl, trigger, options === null || options === void 0 ? void 0 : options.debounce]); return { data, error, loading, reload }; }