Offline-First Architecture — Mobile

Offline-First di Mobile Mobile user sering kehilangan koneksi — di lift, tunnel, area remote. Offline-first berarti app tetap fungsional tanpa internet, dan…

Offline-First di Mobile

Mobile user sering kehilangan koneksi — di lift, tunnel, area remote. Offline-first berarti app tetap fungsional tanpa internet, dan sync saat koneksi kembali.

Prinsip Offline-First

Network Detection

import NetInfo from '@react-native-community/netinfo';

// Cek status sekali
const state = await NetInfo.fetch();
console.log('Connected:', state.isConnected);
console.log('Type:', state.type); // wifi, cellular, none

// Subscribe ke perubahan
const unsubscribe = NetInfo.addEventListener(state => {
  if (state.isConnected) {
    // Sync pending operations
    syncQueue.flush();
  }
});

Mutation Queue Pattern

// Simpan operasi yang belum bisa dijalankan
class OfflineQueue {
  constructor(storage) {
    this.storage = storage;
  }

  async enqueue(operation) {
    const queue = JSON.parse(
      await this.storage.getItem('offline_queue') || '[]'
    );
    queue.push({
      id: Date.now().toString(),
      operation,
      timestamp: new Date().toISOString(),
      retries: 0,
    });
    await this.storage.setItem('offline_queue', JSON.stringify(queue));
  }

  async flush() {
    const queue = JSON.parse(
      await this.storage.getItem('offline_queue') || '[]'
    );

    for (const item of queue) {
      try {
        await executeOperation(item.operation);
        // Hapus dari queue jika berhasil
      } catch (error) {
        item.retries += 1;
        if (item.retries >= 3) {
          // Move to dead letter queue
        }
      }
    }
  }
}

TanStack Query Offline Support

import { onlineManager } from '@tanstack/react-query';
import NetInfo from '@react-native-community/netinfo';

// Auto-pause queries saat offline
onlineManager.setEventListener(setOnline => {
  return NetInfo.addEventListener(state => {
    setOnline(!!state.isConnected);
  });
});

// Mutations otomatis di-queue dan retry saat online
const mutation = useMutation({
  mutationFn: createPost,
  // Retry akan otomatis berjalan saat online kembali
  retry: 3,
});

Conflict Resolution Strategies

Yang akan kamu pelajari