Skip to main content

AbortController

Cancel in-flight requests using the standard AbortController API.

Basic usage​

import { fetch } from 'react-native-nitro-fetch';

const controller = new AbortController();

// Abort after 500ms
setTimeout(() => controller.abort(), 500);

try {
const res = await fetch('https://httpbin.org/delay/20', {
signal: controller.signal,
});
} catch (e) {
if (e.name === 'AbortError') {
console.log('Request was cancelled');
}
}

If the signal has a reason (from controller.abort(reason) or AbortSignal.timeout()), the request rejects with that reason instead of an AbortError, and a streamed body errors with it too. React Native versions whose AbortController has no reason support always get an AbortError.

Pre-aborted signals​

Pre-aborted signals are also supported — the request will throw immediately without making a network call:

const controller = new AbortController();
controller.abort();

await fetch(url, { signal: controller.signal }); // throws AbortError

Timeout pattern​

A common pattern is to create a timeout wrapper:

import { fetch } from 'react-native-nitro-fetch';

async function fetchWithTimeout(url: string, timeoutMs: number) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);

try {
const res = await fetch(url, { signal: controller.signal });
return res;
} finally {
clearTimeout(timer);
}
}
tip

The AbortController API works exactly like the browser standard. If you're already using it with the built-in fetch, no changes are needed.

Nitro Fetch is built with ❤️ by Margelo. We build fast and beautiful apps. Contact us at margelo.com for high-end consultancy services.