Skip to content

Instantly share code, notes, and snippets.

@ashutosh887
Created April 23, 2022 04:47
Show Gist options
  • Save ashutosh887/20f930d3d01087dc4e39a1cdab60c825 to your computer and use it in GitHub Desktop.
Save ashutosh887/20f930d3d01087dc4e39a1cdab60c825 to your computer and use it in GitHub Desktop.
Custom Hook for React HTTP Calls
// 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