In Mrs. Rini's shop, the signal near the counter often drops. If the app treats that as an error, every tap there ends on an error screen. An offline-first app treats it as a normal state: it reads and writes on the phone first, then brings its data in line with the server once there is signal. Mrs. Rini's cashier has long worked this way with the message book on the counter. When the call to the courier cuts out, the cashier writes "pick up Wulan at 16:00, number J-7f3a", then calls again once the line is back. Because every entry has a number, the courier doesn't come twice even if the cashier called twice. In the app, that book is called an outbox, and the number is a client id.
What data lives on the phone
| Data | Stored in | When it differs from the server |
|---|---|---|
| Wulan's order #13 | the TanStack Query cache in REACT_QUERY_OFFLINE_CACHE (local storage lesson) |
the server wins |
| The "Ironing" filter | Zustand persist, key orders-filter |
not on the server |
| Pickup requests not sent yet | the outbox: paused mutations, saved in the same cache | resent until the server answers |
| The login token | expo-secure-store |
log in again |
For this customer app, the persisted query cache is enough as the data on the phone: there's little of it (one account's active orders), the phone only reads it, and order status belongs to Mrs. Rini's board. expo-sqlite only pays off when the phone keeps thousands of rows to search and filter without signal, or changes a lot of data itself. Think of a cashier app that records 300 receipts a day. There SQLite becomes the source of truth on the phone, and you write the sync code yourself.
Reading while offline
TanStack Query needs to know whether the phone is online. On the web it reads browser events. React Native has none, so connect @react-native-community/netinfo (12.0.1, what npx expo install installs on SDK 57) to onlineManager:
// src/lib/online.ts (imported once in src/app/_layout.tsx)
import NetInfo from '@react-native-community/netinfo';
import { onlineManager } from '@tanstack/react-query';
onlineManager.setEventListener((setOnline) =>
NetInfo.addEventListener((state) => {
setOnline(state.isConnected === true && state.isInternetReachable !== false);
}),
);
By default a query uses networkMode: 'online': while offline, the query doesn't run but is held (fetchStatus: 'paused'), and data from the cache keeps showing. Once online, the query refetches by itself.
const { data, isPending, fetchStatus, dataUpdatedAt } = useQuery({ queryKey: ['orders', 'mine'], queryFn: fetchMyOrders });
const offline = fetchStatus === 'paused';
if (isPending) return offline ? <Text>Offline, and no data on the phone yet.</Text> : <ActivityIndicator />;
// offline with a cache: show "Offline. Data from the phone, last updated 14:05." above the list
fetchStatus: 'paused'withdatafilled: #13 "Ironing" from the cache, plus the time fromdataUpdatedAt.isPendingwithfetchStatus: 'paused': never had data and no signal. Show a message, not a spinner forever.networkMode: 'always'runs the request even offline (it's bound to fail).'offlineFirst'tries once first, useful on the web with a service worker.
What "online" means
| Phone state | isConnected |
isInternetReachable |
onlineManager |
|---|---|---|---|
| Airplane mode | false |
false |
offline |
| Café Wi-Fi that wants a login first (captive portal) | true |
false |
offline |
| Just connected, not checked yet | true |
null |
online (try it) |
| Normal signal | true |
true |
online |
Connected to Wi-Fi doesn't mean connected to the internet. On Android, isInternetReachable comes from the system (a network that is "validated"). On iOS, NetInfo checks it itself: a HEAD request to https://clients3.google.com/generate_204, counted as internet when the answer is 204, repeated every 60 seconds while online and every 5 seconds while not. The café's login page answers with its own page, not a 204. You can point that check at your own server with NetInfo.configure({ reachabilityUrl, reachabilityTest }). Still, the last word belongs to the request itself: even "online" can fail, so a network failure is treated like being offline, which means trying again.
The outbox: a queue of writes
A TanStack Query mutation run while offline doesn't fail, it's held (isPaused: true). The persister saves held mutations with the cache, so the queue survives the app being closed. The condition is that the send function is registered with setMutationDefaults, because functions can't be saved as JSON:
// src/lib/pickup.ts
export function newPickup(time: string): Pickup {
return { clientId: Crypto.randomUUID(), time }; // expo-crypto: the id is made ONCE, when the button is tapped
}
export function registerPickup(queryClient: QueryClient) {
queryClient.setMutationDefaults(['pickup'], {
mutationFn: sendPickup, // POST /api/me/pickups with { client_id, time }
scope: { id: 'pickup' }, // sent one at a time, in order
retry: (failureCount, error) => !(error instanceof SendError && error.status < 500) && failureCount < 5,
});
}
// src/app/_layout.tsx
<PersistQueryClientProvider client={queryClient} persistOptions={{ persister, maxAge: 1000 * 60 * 60 * 24 }}
onSuccess={() => queryClient.resumePausedMutations()}>
// the button
const pickup = useMutation<{ id: number }, Error, Pickup>({ mutationKey: ['pickup'] });
<Button title="Request a pickup at 16:00" onPress={() => pickup.mutate(newPickup('16:00'))} />
sendPickupis likefetchMyOrdersfrom the API lesson, but aPOSTwith the body{"client_id":"…","time":"16:00"}, and it throwsSendErrorwhen!res.ok.- When the signal returns,
onlineManagerwakes the query client, which runs the held mutations. When the app is reopened,resumePausedMutations()inonSuccessruns them. retry: a dropped connection or a 5xx from the server is tried again up to 5 times, waiting 1, 2, 4, 8, then 16 seconds (Math.min(1000 * 2 ** n, 30000)). If the phone goes offline during a wait, the attempt is held until it's online. A 4xx answer (say 422, a time outside opening hours) won't succeed however often it's repeated, so it fails at once.useMutationState({ filters: { mutationKey: ['pickup'], status: 'pending' } })gives you the queue to show: "Pickup 16:00: waiting for signal".
One request, one pickup: the client id
A request can reach the server while its reply gets lost: the app waits 10 seconds (AbortSignal.timeout), counts it as failed, then sends it again. With no marker, the server records two pickups. With client_id, the server recognises the resend:
// routes/api.php, in the auth:sanctum group (column client_id: $table->uuid('client_id')->unique())
Route::post('/me/pickups', function (Request $request) {
$data = $request->validate(['client_id' => ['required', 'uuid'], 'time' => ['required', 'date_format:H:i']]);
$pickup = $request->user()->pickups()->firstOrCreate(['client_id' => $data['client_id']], ['time' => $data['time']]);
return response()->json(['data' => ['id' => $pickup->id]], $pickup->wasRecentlyCreated ? 201 : 200);
});
Guess first: Wulan taps "Request pickup" with no signal, the signal comes back briefly, the request arrives but the reply is lost, and the app sends it again. With the code above, how many pickup requests does the courier see?
| Send | Server | App |
|---|---|---|
1: client_id 7f3a… |
new row, 201, reply lost |
timeout, retry 1 second later |
2: the same client_id 7f3a… |
the row already exists, 200 with the same id |
sent |
So the courier sees one request. A key like this is called an idempotency key: sending twice has the same result as sending once. If two sends arrive at the same moment, Laravel's firstOrCreate catches the unique index violation and fetches the existing row.
Conflicts: who wins
A conflict happens when the data on the phone and on the server change separately. The common strategies:
| Strategy | How it works | Fits |
|---|---|---|
| Server wins | the server's data overwrites the phone | order #13's status (owned by Mrs. Rini's board) |
| Client wins | the phone's data overwrites the server | personal drafts, settings |
| Last-write-wins | the newest timestamp wins, the other is lost | simple data two people rarely change |
| Merge | combined field by field | notes changed in different fields |
| Manual | the user chooses | important documents |
| Version number | the server rejects a send from an old version, the client refetches and tries again | data many people change |
In this app, the phone never changes an order's status. Offline, #13 shows "Ironing" from the cache, while Mrs. Rini has already moved it to "Ready for pickup". Once online, the query refetches and the server wins. Pickup requests are only added, never changed, so their problem isn't conflicts but duplicates, which client_id solves.
Testing without signal
- Android emulator:
adb shell svc wifi disableandadb shell svc data disable(restore withenable), or the Cellular section of Extended Controls. - iOS Simulator: it uses the Mac's network and has no airplane mode. Turn off the Mac's Wi-Fi, or use Network Link Conditioner (from Additional Tools for Xcode) with the "100% Loss" profile.
- A real phone: airplane mode, or on an iPhone, Settings > Developer > Network Link Conditioner.
- The test order: open the app with no signal (the cache shows), request a pickup (it's queued), close and reopen the app (the queue is still there), turn the signal on (sent once, #13 refreshed from the server).
⚠️ Queues that get lost, doubled or never sent
- Checking only
isConnected. On a café Wi-Fi that wants a login, the app thinks it's online, the request keeps failing, and after 5 retries the request is dropped. Also requireisInternetReachable !== false. - Making the client id inside
mutationFn. Every attempt gets a new id, so a resend is recorded as a new pickup. Make the id when the button is tapped and keep it invariables. - Forgetting
setMutationDefaultsandresumePausedMutations. The queue is saved, but after a reopen there's no function to send it. - Retrying 4xx answers. A
422stays a422if you send it a hundred times. Retry only network failures and 5xx. - An error screen while offline although a cache exists. Use
fetchStatus === 'paused'and show the phone's data with the last update time.
TL;DR: Offline-first means data is stored and read on the phone first, then synced to the server when there's a connection. For Mrs. Rini's Laundry customer app, the persisted TanStack Query cache is enough as the data on the phone (expo-sqlite for thousands of rows or lots of offline changes). Connect NetInfo 12.0.1 to onlineManager with isConnected === true && isInternetReachable !== false, because a Wi-Fi with a login page is connected but has no internet. An offline query is held (fetchStatus: 'paused') and shows the cache. Writes go into an outbox: held mutations, saved by the persister, registered with setMutationDefaults, run again when online or through resumePausedMutations(), retried after 1, 2, 4, 8, 16 seconds. Each request carries a client_id (an idempotency key) made when the button is tapped, so a server receiving a resend answers 200 with the same row. Conflicts are settled with strategies like server wins (order status), client wins, last-write-wins by timestamp, merge, manual, or version numbers. Test with adb shell svc, Network Link Conditioner and airplane mode.
⚡ The phone first, the server later
Meaning: Offline-first means data is read and written on the phone first, then synced to the server when there's a connection. A signal that drops near the counter is treated as a normal state, not an error. An offline query is held (fetchStatus: 'paused') and keeps showing the cache.
⚡ Connected isn't always online
Write:
onlineManager.setEventListener((setOnline) =>
NetInfo.addEventListener((state) => {
setOnline(state.isConnected === true && state.isInternetReachable !== false);
}),
);
Meaning: A café Wi-Fi that wants a login first is connected (isConnected: true) but has no internet (isInternetReachable: false). So check both.
⚡ One request, one pickup
Guess first: a pickup request reaches the server, but its reply is lost, and the app sends it again with the same client_id. How many pickup requests does the courier see?
One. The server uses firstOrCreate on client_id, so the second send gets a 200 with the same row.
Meaning: client_id is an idempotency key: sending twice has the same result as sending once. Make the id when the button is tapped, not inside mutationFn.