Offline writes with the outbox
A project list that keeps working without a connection. Switch to Offline, create a project with its first task and check off a few tasks: every change shows at once and waits in the outbox. Reload the page and it is all still there. Switch back to Online and the outbox sends the writes in the order you made them.
Loading the example...
Run locally
npx tiged BetterTyped/hyper-fetch/examples/db/offline-outbox hyper-fetch-db-offline-outbox && cd hyper-fetch-db-offline-outbox && npm install && npm run devWhat it shows
- An outbox:
createDb(collections, { offline: true })sends every write through a queue that waits for the network and replays in order. - Persistence:
persistence: { storage: localStorage, scope, version }keeps the rows and the outbox, so a reload keeps offline writes on screen and in the queue. - Idempotency keys:
mapsends the write's id fromcontext.id, and the fake server ignores an id it has seen. - Dependent writes: the first task is inserted with
{ dependsOn: [project] }, so a rejected project drops its task without sending it. - Rejected and retried writes: a 422 drops the write and reports it to
db.onError. A 503 keeps it in the outbox and retries it.
How it works
db.tscreates the db withoffline: trueandpersistence. Every write goes through the outbox, online or not, so there is one path for every write.- Each
mutatemapping addsidempotencyKey: idto the payload. The outbox marks a write as sent before its request goes out and sends it again after a reload, so the server needs the key to apply it once. App.tsxturns the network off withsetOnline(false)fromuseAppManager(client). The outbox waits for the client to come back online, then sends the writes one at a time.- The outbox panel reads
db.inspect().outboxand re-renders ondb.onChange. Each record shows whether it was sent and which write it depends on. - Creating a project makes two writes. The task names the project's
TransactionindependsOn. When the server rejects the project with a 422, the db reverts both rows and reports both writes todb.onError. server.tskeeps its rows and log inlocalStoragetoo. Reload the page while a write is in flight: the server already applied it, the outbox sends it again with the same key, and the log shows it was ignored.
When to use it
- Apps used where the connection drops: field work, travel, mobile.
- Forms and notes where a lost write is expensive.
- Writes that depend on each other, like a project and its tasks, and must reach the server in order.
Related
Summary
You queued writes in a persisted outbox, replayed them in order when the network came back, sent an idempotency key with each one, and let a rejected write take its dependent writes with it.