Use timeout
in the fetch-native options with this drop-in replacement.
import { fetch } from '@/...';
const response = await fetch(
'https://google.com/',
{
method: 'GET',
timeout: 1000, // ms
}
);
// const data = await response.json();
// ...
export const fetch = async (
url: string,
{ timeout = 5000, ...fetchOptions }: RequestInit & { timeout?: number } = {}
) => {
const controller = new AbortController();
const abort = setTimeout(() => {
controller.abort();
Promise.reject(
new Error(`Request to ${url} timed out after ${timeout}ms.`)
);
}, timeout);
try {
const response = await globalThis.fetch(url, {
...fetchOptions,
signal: controller.signal,
});
clearTimeout(abort);
return response;
} catch (error: any) {
if (error?.name === 'AbortError') {
throw new Error(`Request to ${url} timed out after ${timeout}ms.`);
} else {
throw error;
}
}
};