Created
June 27, 2019 18:10
-
-
Save 197291/5d6c170b64979b99c758bd622b5e8ff5 to your computer and use it in GitHub Desktop.
React Hooks
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
const useFetch = (url) => { | |
const [data, setData] = useState(null); | |
useEffect(() => { | |
let mounted = true; | |
const abortController = new AbortController(); | |
(async () => { | |
const res = await fetch(url, { | |
signal: abortController.signal, | |
}); | |
const data = await res.json(); | |
if (mounted) setData(data); | |
})(); | |
const cleanup = () => { | |
mounted = false; | |
abortController.abort(); | |
}; | |
return cleanup; | |
}, [url]); | |
return data; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment