UNPKG

arcx

Version:

A lightweight, dependency-free fetch utility for APIs and React.

44 lines (43 loc) 1.44 kB
"use strict"; "use client"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useFetch = useFetch; /** * @module useFetch * A React hook for fetching data using `fetchRequest`. */ const react_1 = require("react"); const fetchRequest_1 = require("./fetchRequest"); /** * Provides data, loading state, error state, and a `refetch` function for * a given URL and options. Uses the ArcX fetchRequest under the hood. * * @template T - The expected shape of the fetched data. * @param url - The endpoint or path for the request. * @param options - Additional ArcX/React options (manual, etc.). */ function useFetch(url, options) { const [data, setData] = (0, react_1.useState)(null); const [isLoading, setIsLoading] = (0, react_1.useState)(false); const [error, setError] = (0, react_1.useState)(null); const fetchData = (0, react_1.useCallback)(async () => { setIsLoading(true); setError(null); try { const result = await (0, fetchRequest_1.fetchRequest)(url, options ?? {}); setData(result); } catch (err) { setError(err); } finally { setIsLoading(false); } }, [url, options]); (0, react_1.useEffect)(() => { if (!options?.manual) { void fetchData(); } }, [fetchData, options?.manual]); return { data, isLoading, error, refetch: fetchData }; }