From 1a3d46dbf75267d6ae363169d1a1562234a1cf28 Mon Sep 17 00:00:00 2001 From: rray524 Date: Tue, 24 Dec 2024 18:50:10 +0530 Subject: [PATCH] create useFetch hook 1.0 --- src/hooks/useFetch.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/hooks/useFetch.js diff --git a/src/hooks/useFetch.js b/src/hooks/useFetch.js new file mode 100644 index 0000000..378bf67 --- /dev/null +++ b/src/hooks/useFetch.js @@ -0,0 +1,37 @@ +import { useState, useEffect, useCallback } from "react"; + +const useFetch = (url, options = {}, autoFetch = true) => { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(false); + + const fetchData = useCallback(async () => { + setLoading(true); + setError(null); + + try { + const response = await fetch(url, options); + + if (!response.ok) { + throw new Error(`Error: ${response.status} ${response.statusText}`); + } + + const responseData = await response.json(); + setData(responseData); + } catch (err) { + setError(err.message); + } finally { + setLoading(false); + } + }, [url, options]); + + useEffect(() => { + if (autoFetch) { + fetchData(); + } + }, [fetchData, autoFetch]); + + return { data, error, loading, refetch: fetchData }; +}; + +export default useFetch;