Created
August 7, 2023 14:12
-
-
Save KrofDrakula/c4cb0fc7fd065feda41cc3c15d636509 to your computer and use it in GitHub Desktop.
Abortable `fetch`
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
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), | |
}) |
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
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