GuidesMobile apps
A mobile app that works offline
The principle
- 1Write locallyEvery action is saved on the phone.
- 2QueueThe change waits to be sent.
- 3SyncWhen the network returns, in order.
- 4PullChanges made by others.
The queue
type Operation = { id: string; type: 'create' | 'update' | 'delete'; table: string; data: unknown; attempts: number };
async function sync() {
const ops = await db.getAllAsync<Operation>('SELECT * FROM queue ORDER BY rowid');
for (const op of ops) {
const r = await fetch(`${API}/sync`, { method: 'POST', body: JSON.stringify(op) }).catch(() => null);
if (!r?.ok) break; // retry when the network comes back
await db.runAsync('DELETE FROM queue WHERE id = ?', op.id);
}
}
Rules that prevent trouble
| Rule | Why |
|---|---|
| IDs created on the phone (UUID) | No server needed to create a record |
| Idempotent operations | A resend does not create a duplicate |
| Timestamp on every change | To settle conflicts |
| Visible “waiting to send” indicator | Users know where they stand |
Conflicts
- Last write winsSimple, enough for personal notes.
- The server decidesFor stock or payments.
- Merge by fieldTwo people, two different fields: keep both.
The starting choice: Expo or native development. The journey: building a mobile app.
Frequently asked questions
- What happens if two people edit the same data?
- You need a written rule: last write wins, the server decides, or both versions are merged field by field. The choice depends on the business.
- Which local database should I use?
- SQLite (for example with expo-sqlite) fits most cases. Sync libraries exist for heavier needs.
- How do I know if the device is online?
- A library like NetInfo reports changes. Do not rely on it alone: a failed request is still the real test.