Skip to content

Instantly share code, notes, and snippets.

@KrofDrakula
Created August 7, 2023 14:12
Show Gist options
  • Save KrofDrakula/c4cb0fc7fd065feda41cc3c15d636509 to your computer and use it in GitHub Desktop.
Save KrofDrakula/c4cb0fc7fd065feda41cc3c15d636509 to your computer and use it in GitHub Desktop.
Abortable `fetch`
export const isAbortError = (err: unknown): err is Error =>
(err as Error)?.name == 'AbortError'
export const abortableFetch = (
url: RequestInfo | URL,
options?: RequestInit | undefined,
fetchImpl?: typeof fetch
): [promise: Promise<Response>, abort: (reason?: any) => void] => {
const controller = new AbortController()
options = { ...options, signal: controller.signal }
return [(fetchImpl ?? fetch)(url, options), controller.abort]
}
export const timeoutFetch = (
timeout: number,
url: RequestInfo | URL,
options?: RequestInit | undefined,
fetchImpl?: typeof fetch
) =>
(fetchImpl ?? fetch)(url, {
...options,
signal: AbortSignal.timeout(timeout),
})
import { abortableFetch, isAbortError } from './abortable-fetch.ts';
function MyComponent() {
const [data, setData] = useState();
useEffect(
() => {
const [promise, abort] = abortableFetch('https://example.com');
promise.then(response => response.json()).then(received => setData(received));
return () => abort();
},
[]
);
return <>...</>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment