UNPKG

use-minimal-fetch

Version:

A lightweight useFetch hook with Axios wrapper for React apps

29 lines (28 loc) 827 B
import { useEffect, useState } from "react"; import api from "../lib/api"; export const useFetchHook = (url, options = {}) => { const { lazy = false, params, headers } = options; const [data, setData] = useState(null); const [loading, setLoading] = useState(!lazy); const [error, setError] = useState(null); const fetchData = async () => { setLoading(true); try { const res = await api.get(url, { params, headers }); setData(res.data); setError(null); } catch (err) { setError(err); setData(null); } finally { setLoading(false); } }; useEffect(() => { if (!lazy) fetchData(); }, [url]); return { data, loading, error, refetch: fetchData }; };