Created
November 30, 2022 16:26
-
-
Save ashybaye/5bbd5bed0d6c22439bbf0472b595164f 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