UNPKG

arcx

Version:

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

41 lines (40 loc) 1.28 kB
"use client"; /** * @module useFetch * A React hook for fetching data using `fetchRequest`. */ import { useState, useEffect, useCallback } from "react"; import { fetchRequest } from "./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.). */ export function useFetch(url, options) { const [data, setData] = useState(null); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const fetchData = useCallback(async () => { setIsLoading(true); setError(null); try { const result = await fetchRequest(url, options ?? {}); setData(result); } catch (err) { setError(err); } finally { setIsLoading(false); } }, [url, options]); useEffect(() => { if (!options?.manual) { void fetchData(); } }, [fetchData, options?.manual]); return { data, isLoading, error, refetch: fetchData }; }