Last active
October 26, 2022 20:59
-
-
Save DominikStyp/41b5a5fdff9795121a36cf15466a5aff to your computer and use it in GitHub Desktop.
React: useFetch() helper, abort fetch() using AbortController
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 { useEffect, useState } from "react"; | |
expoprt function useFetch(url) { | |
const [loading, setLoading] = useState(true); | |
const [data, setData] = useState(null); | |
const [error, setError] = useState(null); | |
useEffect(() => { | |
controller = new AbortController(); | |
const signal = controller.signal; | |
fetch(url, { signal }) | |
.then((response) => { | |
setData(response.data); | |
}) | |
.catch(setError) | |
.finally(() => setLoading(false)); | |
return () => { | |
controller.abort(); // here we abort the previous fetch request which could start but didn't finish | |
}; | |
}, [url]); | |
return { loading, data, error }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment