Offline Mutation Queue

Reliably capture user actions (likes, form submissions, comments) when the device has no internet connection, and replay them sequentially with idempotency guarantees once connectivity is restored.


How the Offline Queue Works

The createOfflineQueue() factory provides a persistent FIFO queue specifically designed for mobile applications. When requests are enqueued:

  • Each queued request is assigned a unique UUID Idempotency-Key header to prevent duplicate backend execution.
  • Requests are persisted to your chosen storage adapter (MemoryStorageAdapter, MMKV, or AsyncStorage).
  • When queue.process() is called (e.g. via NetInfo network listener), requests are replayed in exact chronological sequence.
offline-service.ts
typescript
import { createClient, createOfflineQueue, MemoryStorageAdapter } from 'react-native-fetch-client';
import NetInfo from '@react-native-community/netinfo';

const api = createClient({ baseURL: 'https://api.example.com' });

// 1. Create offline queue with persistence
export const offlineQueue = createOfflineQueue({
  client: api,
  storage: new MemoryStorageAdapter(), // Or custom MMKV / AsyncStorage adapter
  maxRetries: 5,
  onProcessSummary: (summary) => {
    console.log(`Queue processed: ${summary.succeeded} succeeded, ${summary.failed} failed`);
  },
});

// 2. Queue mutation when user is offline
async function likePost(postId: string) {
  await offlineQueue.enqueue({
    url: `/posts/${postId}/like`,
    method: 'POST',
    body: { timestamp: Date.now() },
  });
  console.log('Action queued offline! Will replay when reconnected.');
}

// 3. Auto-process queue when network returns:
NetInfo.addEventListener(state => {
  if (state.isConnected && state.isInternetReachable) {
    offlineQueue.process();
  }
});
Idempotency Guarantees
Because each item retains its generated Idempotency-Key across app restarts, your backend can safely deduplicate requests even if an unstable connection dropped right before the server sent back the acknowledgment.