Timeouts, Abort & Auto-Cancel

Manage request lifecycles, configure hard timeouts, trigger manual cancellations via AbortController, and leverage automatic race-condition elimination with cancelPrevious.


1. Timeouts

Timeouts are measured in milliseconds. If the server does not finish sending the response within the timeframe, a TimeoutError is thrown and the underlying network connection is cleanly aborted:

typescript
import { createClient } from 'react-native-fetch-client';

const api = createClient({
  baseURL: 'https://api.example.com',
  timeout: 5000, // Client-level default
});

// Request-level override: 2500ms
const res = await api.get('/fast-endpoint', {
  timeout: 2500,
});

2. Standard AbortController

Pass any standard WHATWG AbortSignal to cancel requests when a user navigates away or unmounts a React component:

typescript
const controller = new AbortController();

// Trigger abort after 3 seconds or on screen unmount
const timer = setTimeout(() => controller.abort('User navigated away'), 3000);

try {
  const res = await api.get('/large-dataset', {
    signal: controller.signal,
  });
} catch (err) {
  if (isCancelError(err)) {
    console.log('Request was cancelled:', err.cause);
  }
} finally {
  clearTimeout(timer);
}

3. Autocomplete Auto-Cancel (cancelPrevious)

In rapid search inputs or tab switchers, use a shared string key to cancel the previous pending request in that group:

typescript
// Perfect for search inputs!
async function onSearchInput(query: string) {
  // A newer request in the same cancellation group aborts its pending predecessor.
  const res = await api.get('/search', {
    params: { q: query },
    cancelPrevious: 'search',
  });

  renderSearchResults(res.data);
}
Client-Scoped Isolation
Cancellation groups are strictly isolated to the client instance returned by createClient(). Separate client instances reusing the same group key (e.g. 'search') will never cancel each other's requests.
Using cancellation groups
Cancellation helps prevent an older pending request from updating the UI after a newer one. Handle the cancellation error in your application, and use the same key only for requests that should replace one another within the same client.