Skip to content

Instantly share code, notes, and snippets.

@thathurtabit
Created June 29, 2021 09:33
Show Gist options
  • Save thathurtabit/0eed2c8568c409a5dd6a757c29f9564f to your computer and use it in GitHub Desktop.
Save thathurtabit/0eed2c8568c409a5dd6a757c29f9564f to your computer and use it in GitHub Desktop.
React: Fetch Hook (with AbortController to avoid race conditions and memory leaks)
import { useState, useEffect } from "react";
/* H/T:
Avoiding Race Conditions and Memory Leaks in React useEffect
https://javascript.plainenglish.io/avoiding-race-conditions-and-memory-leaks-in-react-useeffect-2034b8a0a3c7
*/
interface IUseFetchWithAbortResponse {
fetchedData: unknown;
isLoading: boolean;
error: Error | null;
}
export const useFetchWithAbort = (
endpoint: string,
options?: ResponseInit
): IUseFetchWithAbortResponse => {
const [fetchedData, setFetchedData] = useState();
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let abortController = new AbortController();
const fetchData = async () => {
try {
const response = await fetch(endpoint, {
...options,
signal: abortController.signal,
});
const newData = await response.json();
setIsLoading(false);
setFetchedData(newData);
} catch (error) {
if (error.name === "AbortError") {
setError(error);
setIsLoading(false);
}
}
};
fetchData();
return () => {
abortController.abort();
};
}, [endpoint, options]);
return { fetchedData, isLoading, error };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment