UNPKG

qol-hooks

Version:

A collection of React hooks to improve the quality of life of developers.

64 lines (63 loc) 2.39 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { useState, useEffect } from "react"; /** * @description A hook to fetch data from an API * @param {string | (() => string)} url The URL to fetch data from * @param {RequestInit} options The fetch options * @returns {FetchResult} The data, loading state, and error * * @example```tsx * const [data, loading, error] = useFetch("https://api.example.com/data", { * method: "GET", * headers: { * "Content-Type": "application/json", * }, * }); * if (loading) { * return <p>Loading...</p>; * } * if (error) { * return <p>Error: {error.message}</p>; * } * return <pre>{JSON.stringify(data, null, 2)}</pre>; * ``` */ function useFetch(url, options) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = () => __awaiter(this, void 0, void 0, function* () { setLoading(true); try { const fetchUrl = typeof url === "function" ? url() : url; const response = yield fetch(fetchUrl, options); if (!response.ok) { throw new Error(response.statusText); } const result = yield response.json(); setData(result); } catch (error) { if (error instanceof Error) { setError(error); } else { setError(new Error(String(error))); } } setLoading(false); }); fetchData(); }, [url, options]); return [data, loading, error]; } export default useFetch;