Skip to content

Instantly share code, notes, and snippets.

@DominikStyp
Last active October 26, 2022 20:59
Show Gist options
  • Save DominikStyp/41b5a5fdff9795121a36cf15466a5aff to your computer and use it in GitHub Desktop.
Save DominikStyp/41b5a5fdff9795121a36cf15466a5aff to your computer and use it in GitHub Desktop.
React: useFetch() helper, abort fetch() using AbortController
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