import { useCallback, useEffect, useRef, useState } from "react";
export interface UseFetchOptions extends RequestInit {
autoInvoke?: boolean;
}
export function useFetch<T>(
url: string,
{ autoInvoke = true, ...options }: UseFetchOptions = {},
) {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const controller = useRef<AbortController | null>(null);
const refetch = useCallback(() => {
if (!url) {
return;
}
if (controller.current) {
controller.current.abort();
}
controller.current = new AbortController();
setLoading(true);
return fetch(url, { signal: controller.current.signal, ...options })
.then((res) => res.json())
.then((res) => {
setData(res);
return res as T;
})
.catch((err) => {
if (err.name !== "AbortError") {
setError(err);
}
return err;
})
.finally(() => {
setLoading(false);
});
}, [url]);
const abort = useCallback(() => {
if (controller.current) {
controller.current.abort("");
}
}, []);
useEffect(() => {
if (autoInvoke) {
refetch();
}
return () => {
if (controller.current) {
controller.current.abort("");
}
};
}, [refetch, autoInvoke]);
return { data, loading, error, refetch, abort };
}
Associated Context | |
---|---|
Type | Code Snippet ( .js ) |
Associated Tags | React Hooks UseFetchOptions useCallback useEffect useRef useState RequestInit AbortController abortError Framework: React React Hook Fetch Data Fetching API Asynchronous TypeScript |
💡 Smart Description | This code snippet defines a custom React hook called UseFetchOptions. It uses the useCallback and useEffect hooks to fetch data, loading, error, refetch errors, or abort an AbortController if it is not already loaded yet A custom React hook for fetching data from an API using the Fetch API and managing loading, error, and abort states. |
🔎 Suggested Searches | How to handle errors in React fetch API abortcontroller Example code for creating an AbortController instance in React custom hook fetch Implementing abort requests in React using RequestInit data fetching react typescript hook usefetch Code snippet for fetching data from a URL and handling error responsesin React React useFetch function with requestInit api |
Related Links | https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then https://javascript.info/promise-error-handling https://react-redux.js.org/api/hooks#useselector https://react-redux.js.org/api/hooks https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch |
Related People | Emmanuel Isenah |
Sensitive Information | No Sensitive Information Detected |
Shareable Link | https://1cb3ec25-9428-464f-85f1-d2e34661bab4.pieces.cloud/?p=32234ab6e0 |