Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Http Request hook/fetch_hook.js
Original file line number Diff line number Diff line change
@@ -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;