Created
January 7, 2023 12:46
-
-
Save skinnyfads/3c37bee24d543fcb9735c7217cdbd8d2 to your computer and use it in GitHub Desktop.
React useFetch on TypeScript
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: string, options: any) => { | |
const [response, setResponse] = useState<string | undefined>(undefined); | |
const [error, setError] = useState<unknown>(undefined); | |
const [abort, setAbort] = useState<() => void>(() => {}); | |
useEffect(() => { | |
const fetchData = async () => { | |
try { | |
const abortController = new AbortController(); | |
const signal = abortController.signal; | |
setAbort(abortController.abort); | |
const res = await fetch(url, { ...options, signal }); | |
const json = await res.json(); | |
setResponse(json); | |
} catch (error: unknown) { | |
setError(error); | |
} | |
}; | |
fetchData(); | |
return () => { | |
abort(); | |
}; | |
}, []); | |
return { response, error, abort }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment