Created
April 23, 2022 04:47
-
-
Save ashutosh887/20f930d3d01087dc4e39a1cdab60c825 to your computer and use it in GitHub Desktop.
Custom Hook for React HTTP Calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// useCustomHTTP HOOK | |
// To reuse our Custom HTTP Request Logic in across multiple components | |
import { useCallback, useState } from "react"; | |
const useCustomHTTP = () => { | |
const [isLoading, setIsLoading] = useState(false); | |
const [error, setError] = useState(null); | |
const sendHTTPRequest = useCallback(async (requestConfig, applyData) => { | |
setIsLoading(true); | |
setError(null); | |
try { | |
const response = await fetch(requestConfig.url, { | |
method: requestConfig.method ? requestConfig.method : "GET", | |
headers: requestConfig.headers ? requestConfig.headers : {}, | |
body: JSON.stringify(requestConfig.body) | |
? JSON.stringify(requestConfig.body) | |
: null, | |
}); | |
if (!response.ok) { | |
throw new Error("Request Failed. Response not OK!"); | |
} | |
const data = await response.json(); | |
applyData(data); | |
} catch (err) { | |
setError(err.message || "Something went wrong..."); | |
} | |
setIsLoading(false); | |
}, []); | |
return { | |
isLoading: isLoading, | |
error: error, | |
sendHTTPRequest: sendHTTPRequest, | |
}; | |
}; | |
export default useCustomHTTP; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment