Skip to content

Instantly share code, notes, and snippets.

@skinnyfads
Created January 7, 2023 12:46
Show Gist options
  • Save skinnyfads/3c37bee24d543fcb9735c7217cdbd8d2 to your computer and use it in GitHub Desktop.
Save skinnyfads/3c37bee24d543fcb9735c7217cdbd8d2 to your computer and use it in GitHub Desktop.
React useFetch on TypeScript
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