Last active
November 4, 2022 00:19
-
-
Save haikelfazzani/ec571fcdec94a315abae07512611733a to your computer and use it in GitHub Desktop.
useFetch React and Preact hook with 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
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