UNPKG

@mantine/hooks

Version:

A collection of 50+ hooks for state and UI management

46 lines (45 loc) 1.27 kB
"use client"; let react = require("react"); //#region packages/@mantine/hooks/src/use-fetch/use-fetch.ts function useFetch(url, { autoInvoke = true, ...options } = {}) { const [data, setData] = (0, react.useState)(null); const [loading, setLoading] = (0, react.useState)(false); const [error, setError] = (0, react.useState)(null); const controller = (0, react.useRef)(null); const refetch = (0, react.useCallback)(() => { if (controller.current) controller.current.abort(); controller.current = new AbortController(); setLoading(true); return fetch(url, { signal: controller.current.signal, ...options }).then((res) => res.json()).then((res) => { setData(res); setLoading(false); return res; }).catch((err) => { setLoading(false); if (err.name !== "AbortError") setError(err); return err; }); }, [url]); const abort = (0, react.useCallback)(() => { if (controller.current) controller.current?.abort(""); }, []); (0, react.useEffect)(() => { if (autoInvoke) refetch(); return () => { if (controller.current) controller.current.abort(""); }; }, [refetch, autoInvoke]); return { data, loading, error, refetch, abort }; } //#endregion exports.useFetch = useFetch; //# sourceMappingURL=use-fetch.cjs.map