-
-
Save mhmtugur/202c3626c8dc74fd969f748bfc387ce7 to your computer and use it in GitHub Desktop.
React: Fetch Hook (with AbortController to avoid race conditions and memory leaks)
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
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