Local Persistence & Drafts
Learning Objectives
- You can save and load a local proposal while handling storage failure.
- You can distinguish a completed local save from server acceptance.
- You can scope drafts to an identity and ignore results belonging to an old view.
An editor contains an unsent title change based on document version 3. If the connection is lost, it can preserve that proposal on this device without changing the server. The document example from the private-load chapter now lets us distinguish three things: the text in an input, a stored local copy and the version accepted by the server.
Wait for the local operation
The exercise supplies a store with two operations:
| Call | Fulfilled result |
|---|---|
storage.save(record) | The local save has completed. |
storage.load(key) | The saved draft, or undefined if none exists. |
Both return promises and can reject. Await the result before reporting success. For example, these statements run in order inside an async handler:
await storage.save(record);status = "Saved on this device.";If saving rejects, execution moves to the catch, which reports failure and retains the proposal. Figure 1 follows those outcomes.
The same rule applies when removing a stored copy: wait for
storage.remove(key) before reporting removal success. Deleting a stored copy
and clearing the input are separate choices.
Deletion feedback
0 / 5 points
The editor calls storage.remove(key) to delete a local draft. Its returned promise rejects, and the proposed title is still visible in the input. Which feedback and input behavior should the editor use?
Browser storage is accessed from browser interactions. A server load cannot read a draft stored on the visitor’s device. The supplied implementation handles the storage API; your task uses the save/load contract above.
Identify the record and the current view
A draft contains its key, title, baseVersion and savedAt. The supplied
makeDraft helper creates that record with a timestamp. Its key combines stable
user and document identities: Aino/document 12, Aino/document 13 and
Bela/document 12 are separate records. Keys prevent accidental account mixing;
they neither grant server permission nor encrypt local text. Never store
passwords, raw session cookies or authentication tokens in a draft.
Scope asynchronous results to the current view as well as the stored record. Aino’s load can finish after Bela signs in:
| Event | Captured operation token | Current generation | Effect |
|---|---|---|---|
| Aino starts loading document 12. | 6 | 6 | Await the result. |
| Bela signs in. | 6 | 7 | Clear Aino’s visible fields. |
| Aino’s load finishes. | 6 | 7 | Ignore its text, status and pending-state updates. |
The starter advances generation on identity/resource change and captures a
token when an operation begins. Apply updates to text, feedback and pending
state only while the captured token matches the current generation.
A pending operation finishes
0 / 5 points
An editor uses generation to distinguish identity changes. Each read resolves to a string. An old read starts at generation 4. The user then changes, generation becomes 5, and a new read sets busy = true.
The old read finishes before the new one. The active userId is 8, and the old read returns nonempty text.
const loadProposal = async () => { const token = generation; busy = true; const text = await readProposal();
if (token === generation) { title = text; } busy = false;};Replace only the busy = false; statement after the guarded title assignment. Which replacement preserves the new read’s pending state as well as its title?
Save, reload and explicitly restore
Complete the two save/load branches. The starter supplies the store, keys, timestamp helper, pending/failure handling and removal/logout paths. Keep those paths and the generation checks: clearing private fields on logout and removing stored records are separate operations, and removal can fail.
A found draft restores its title and base version; a missing draft keeps the fields and reports that none exists. A restored version-3 proposal remains based on version 3.
The checks follow this operation in the same browser context:
- With Aino/document 12 selected, the editor contains “Monday lab notes” and Base version 3. The browser goes offline while the editor stays open, then the visitor chooses Save on this device. “Saved on this device.” appears only after completion; the proposal remains.
- Reconnecting and reloading the reachable route starts a fresh editor.
- Load local draft restores “Monday lab notes” and base version 3, then reports “Local draft loaded.”
This checks local restoration after a reachable reload. Loading the route still requires network access, and server acceptance requires a separate API operation. Browser storage policy, quota or eviction can remove the local copy later.
Local proposals in the editor
0 / 40 points
Complete only the save and load branches of action in lib/DraftEditor.svelte. The store, identity/resource keys, timestamp helper, controls, pending/failure scaffold, removal and outgoing-user cleanup are supplied. Keep that supplied behavior in place.
Use the runtime storage prop (Store is its TypeScript type):
type Draft = { key: string; title: string; baseVersion: number; savedAt: string;};type Store = { save(draft: Draft): Promise<void>; load(key: string): Promise<Draft | undefined>; remove(key: string): Promise<void>; removeUser(userId: number): Promise<void>;};makeDraft(key, title, baseVersion) creates the record, including an ISO timestamp. Await storage.save with the captured identity/resource key and current proposal. On success keep the fields and say Saved on this device.
Await storage.load(key). A found draft restores its title and baseVersion and says Local draft loaded. A missing draft keeps the fields and says No local draft. Every storage operation can reject; keep the supplied catch/finally feedback and the proposal on failure.
After either awaited operation, apply fields or success feedback only when the captured token still equals generation. A late result for another user or document must not update the new editor or unlock its pending operation.
A restored version-3 proposal remains based on version 3. Aino/document 12, Aino/document 13 and Bela/document 12 are separate records. The test disconnects an open editor and reconnects before reloading the route. The supplied store resolves a save promise only after the local operation completes.
Choose Submit solution. Scoped persistence: 15 points; pending/failure feedback: 10; late identity/resource handling: 15. Removal and logout remain supplied regressions, with no separate award.
Optional reference: the IndexedDB implementation
The supplied store uses IndexedDB, a browser database for structured data.
It performs requests inside transactions. For example,
db.transaction("drafts", "readwrite") opens a transaction, and
transaction.objectStore("drafts").put(draft) starts a write.
A write request can succeed before its transaction finishes. The store therefore resolves its save promise only after transaction completion and rejects on failure, including an abort after request success. Removal follows the same rule. The save/load contract hides these events from the editor.
Keep unrelated network work outside an active IndexedDB transaction; awaiting it does not keep the transaction alive indefinitely. See the IndexedDB guide for transaction lifetime and object stores. The supplied store implements these APIs.
Check Your Understanding
- When may the editor report that a local save succeeded?
- What does restoring text after a reachable reload establish?
- How do the record key and generation guard answer different questions?
- Why does a local version-3 proposal retain version 3?