Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT STORAGE / CHAPTER 06 / Learn / LESSON 09
Theory. Saved data can be damaged: a manual edit, an old version of the app, an interrupted write. On load there are THREE different states:
1. No key (getItem is null) — an empty store, normal on the first visit. 2. A key and valid JSON — data. 3. A key but JSON.parse throws — CORRUPT data.
State 3 is NOT the same as empty. If you show it as an empty list and then save a new record, you overwrite (and lose) the only, maybe repairable, version of the data.
The right model: - Show a clear "load-error" state and do NOT touch the key. - Offer an explicit "Recover" action (a button). Only on click: optionally copy the damaged text into a backup key (expenses-backup), then start with an empty list. - Never delete silently as the only path.
Common mistake: a catch that saves []; a load function that returns [] on error; a Recover button with no backup.
<ul id="list"></ul><p id="status"></p><button id="recover" type="button" disabled>Recover</button>{
"expenses": "{\"id\":1,"
}A load error is not empty. Never overwrite silently — show the problem first.
(empty)Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›