Skip to content

Instantly share code, notes, and snippets.

@0tii
Last active March 7, 2024 12:28
Show Gist options
  • Save 0tii/ff3f153b89fa77b34333a894b3e5abbd to your computer and use it in GitHub Desktop.
Save 0tii/ff3f153b89fa77b34333a894b3e5abbd to your computer and use it in GitHub Desktop.
πŸ”— Expo / React Native `fetch` with a 'native' timeout option

πŸ”— Expo / React Native fetch with a 'native' timeout option

Use timeout in the fetch-native options with this drop-in replacement.

Usage

import { fetch } from '@/...';

const response = await fetch(
  'https://google.com/',
  {
    method: 'GET',
    timeout: 1000, // ms
  }
);
// const data = await response.json();
// ...

Code

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;
    }
  }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment