Show contents
Chapter 6 of 7 · 25 min
Project: an offline-first shopping list
By the end of this chapter, you'll be able to
- Design an app that works offline first
- Queue the changes made without a network
- Sync with a server when the connection comes back
- Resolve a conflict between two concurrent changes
Offline first
An offline-first app does not take the network for granted: every action is first applied locally, so it is visible immediately, then sent to the server when possible. In a real PWA, local data lives in IndexedDB (a database in the browser) and syncing goes through fetch; here, we simulate the phone, the network and the server with simple objects, to focus on the logic.
The queue
const server = { items: { rice: { done: false, changed: 100 } } };
function createPhone() {
return { items: structuredClone(server.items), queue: [], online: false };
}
function change(phone, name, done, time) {
phone.items[name] = { done, changed: time };
phone.queue.push({ name, done, changed: time });
}
function sync(phone) {
if (!phone.online) return `offline: ${phone.queue.length} change(s) waiting`;
const sent = phone.queue.length;
for (const c of phone.queue) server.items[c.name] = { done: c.done, changed: c.changed };
phone.queue = [];
phone.items = structuredClone(server.items);
return `${sent} change(s) sent`;
}
const awa = createPhone();
change(awa, "rice", true, 200);
change(awa, "oil", false, 210);
console.log(sync(awa));
awa.online = true;
console.log(sync(awa));
console.log(server.items);
offline: 2 change(s) waiting
2 change(s) sent
{"rice":{"done":true,"changed":200},"oil":{"done":false,"changed":210}}
Offline, nothing is lost: changes wait in the queue, and the local list is already up to date for the user. When the network comes back, the queue is sent, then the phone fetches the server's state, which may contain the changes made by other family members.
The phone fetches the server's state, with everyone else's changes.
Text description of the animation
- At the market, the shopper ticks the rice. No waiting, no spinner.
- The change is applied and saved on the phone.
- Without a network, changes pile up, in order.
- As soon as the connection returns, the queue is sent to the server.
- The phone fetches the server's state, with everyone else's changes.
Conflicts
What happens if two people change the same item while both are offline? A rule is needed, known to everyone. The simplest: the last change wins (last write wins), based on the time of each change.
const server = { milk: { done: false, changed: 100, by: "server" } };
function apply(change) {
const current = server[change.name];
if (current && current.changed > change.changed) {
return `conflict on ${change.name}: ${change.by}'s change (${change.changed}) is older, ignored`;
}
server[change.name] = { done: change.done, changed: change.changed, by: change.by };
return `${change.name}: ${change.done ? "bought" : "to buy"} (by ${change.by})`;
}
console.log(apply({ name: "milk", done: true, changed: 300, by: "Kofi" }));
console.log(apply({ name: "milk", done: false, changed: 250, by: "Awa" }));
console.log(server.milk);
milk: bought (by Kofi)
conflict on milk: Awa's change (250) is older, ignored
{"done":true,"changed":300,"by":"Kofi"}
Awa had unticked the milk at 250, offline; Kofi ticked it at 300. Even though Awa's change reaches the server later, Kofi's, more recent, wins. This rule is simple and predictable, but it can overwrite an intention: other strategies exist (merging fields, asking the user, or data structures designed to merge automatically, called CRDTs).
Mini-lab: cut and restore the networkJavaScript
Output
Click “Run” to execute your code.Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: compacting the queue
After a day offline, the queue holds dozens of changes, often on the same items (ticked, unticked, ticked again). Write a function compact(queue) that keeps, for each item, only the most recent change, in the order of their last change. Less data sent means a faster sync, and a cheaper one on a limited data plan.
const queue = [
{ name: "rice", done: true, changed: 10 },
{ name: "oil", done: false, changed: 11 },
{ name: "rice", done: false, changed: 12 },
{ name: "salt", done: true, changed: 13 },
{ name: "rice", done: true, changed: 14 },
];
Hint 1
Map keeps insertion order: delete then reinsert a key to move it to the end.Hint 2
Show the solution and common mistakes
const queue = [
{ name: "rice", done: true, changed: 10 },
{ name: "oil", done: false, changed: 11 },
{ name: "rice", done: false, changed: 12 },
{ name: "salt", done: true, changed: 13 },
{ name: "rice", done: true, changed: 14 },
];
function compact(list) {
const latest = new Map();
for (const c of list) {
latest.delete(c.name);
latest.set(c.name, c);
}
return [...latest.values()];
}
const compacted = compact(queue);
console.log(`${queue.length} changes → ${compacted.length}`);
for (const c of compacted) console.log(`${c.name}: ${c.done ? "bought" : "to buy"} (${c.changed})`);
5 changes → 3
oil: to buy (11)
salt: bought (13)
rice: bought (14)
The rice was changed three times: only the last version (bought, at 14) is sent. The final result on the server is the same as with the full queue, for much less data.
Common mistakes:
- Keeping the first change for each item instead of the last: an outdated state would be sent.
- Using a plain
{}object without thedelete: the key would keep its original position, and the sending order would no longer reflect the order of the last changes.
Summary
- 1Offline first: every action is applied locally, then synced when the network allows.
- 2A queue keeps the changes made without a network, in order.
- 3When the network returns, send the queue, then fetch the server's shared state.
- 4“The last change wins” resolves conflicts simply, at the risk of overwriting an intention.
- 5Phone clocks are unreliable: prefer a date or version given by the server.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.