Skip to content

Instantly share code, notes, and snippets.

@haikelfazzani
Last active November 4, 2022 00:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haikelfazzani/ec571fcdec94a315abae07512611733a to your computer and use it in GitHub Desktop.
Save haikelfazzani/ec571fcdec94a315abae07512611733a to your computer and use it in GitHub Desktop.
useFetch React and Preact hook with AbortController
export default function useFetch (url, options) {
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const controller = new AbortController();
(async () => {
try {
const res = await fetch(url, { ...options, signal: controller.signal });
const json = await res.json();
setResponse(json);
setIsLoading(false);
} catch (error) {
setError(error);
}
})();
return () => {
controller.abort();
}
}, [url]);
return [ response, error, isLoading ];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment