UNPKG

kwikid-components-react

Version:

KwikID's Component Library in React

72 lines (70 loc) 2.11 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = require("react"); /** * Interface defining the state and methods returned by the useFetch hook */ const useFetch = url => { const [data, setData] = (0, _react.useState)(null); const [loading, setLoading] = (0, _react.useState)(false); const [error, setError] = (0, _react.useState)(null); const abortControllerRef = (0, _react.useRef)(null); const fetchData = async (method, body, headers, queryParams) => { const query = queryParams ? `?${Object.keys(queryParams).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(queryParams[key])}`).join("&")}` : ""; try { setLoading(true); const controller = new AbortController(); abortControllerRef.current = controller; const response = await fetch(`${url}${query}`, { method, headers: { "Content-Type": "application/json", ...headers }, body: method === "POST" ? JSON.stringify(body) : undefined, signal: controller.signal }); if (!response.ok) { throw new Error("Network response was not ok"); } const fetchedData = await response.json(); setData(fetchedData); setLoading(false); } catch (error) { if (error.name !== "AbortError") { setError(error); setLoading(false); } } }; const get = async (headers, queryParams) => { if (abortControllerRef.current) { abortControllerRef.current.abort(); } await fetchData("GET", undefined, headers, queryParams); }; const post = async (body, headers, queryParams) => { if (abortControllerRef.current) { abortControllerRef.current.abort(); } await fetchData("POST", body, headers, queryParams); }; (0, _react.useEffect)(() => { return () => { if (abortControllerRef.current) { abortControllerRef.current.abort(); } }; }, []); return { data, loading, error, get, post }; }; var _default = exports.default = useFetch;