useFetch.ts

import { useEffect, useState } from 'react'; export type UseFetchReturnType<T> = { loading: boolean; data?: T; error?: Error; }; type FetchParameters = Parameters<typeof fetch>; export default function useFetch<T>( url: FetchParameters[0], options: FetchParameters[1], dependencies: Array<unknown> = [], ): UseFetchReturnType<T> { const [loading, setLoading] = useState(true); const [data, setData] = useState<T>(); const [error, setError] = useState<Error>(); const abortController = new AbortController(); useEffect(() => { (async () => { try { const response = await fetch(url, { signal: abortController.signal, ...options }); const data = await response.json(); setData(data); setLoading(false); } catch (e) { if (e instanceof DOMException) { // aborted fetch, don't update UI // this will cause update after unmount exceptions return; } setLoading(false); setError(e); } })(); return () => abortController.abort(); }, dependencies); return { loading, data, error }; }
useFetch with cancellation token

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.