From 4f9de2fc4f3403dd6e4c46ca0ed4e76bbfd382a5 Mon Sep 17 00:00:00 2001 From: Abhishek1438 Date: Tue, 11 Oct 2022 23:14:37 +0530 Subject: [PATCH] initial commit --- Http Request hook/fetch_hook.js | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Http Request hook/fetch_hook.js diff --git a/Http Request hook/fetch_hook.js b/Http Request hook/fetch_hook.js new file mode 100644 index 0000000..9800bae --- /dev/null +++ b/Http Request hook/fetch_hook.js @@ -0,0 +1,34 @@ +import { useState, useCallback } from "react"; + +const useFetch = () => { + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const sendRequest = useCallback(async (requestConfig, applyData) => { + setIsLoading(true); + setError(null); + try { + const response = await fetch(requestConfig.url, { + method: requestConfig.method ? requestConfig.method : "GET", + body: requestConfig.body + ? JSON.stringify(requestConfig.body) + : null, + headers: requestConfig.headers ? requestConfig.headers : {}, + }); + + if (!response.ok) { + throw new Error("Request failed!"); + } + + const data = await response.json(); + applyData(data); + } catch (err) { + setError(err.message || "Something went wrong!"); + } + setIsLoading(false); + }, []); + + return { isLoading, error, sendRequest }; +}; + +export default useFetch;