Restore validated state and handle storage changes
Quick answer
Persist only the data needed to restore a preference. On startup read the stored string, parse inside try/catch, then validate the expected shape and allowed values before using it. Use a safe default for missing, corrupt or incompatible data. A storage event can notify other eligible documents of changes; the document making the write does not receive that event for its own write. Do not rely on storage events as a transactional synchronization mechanism.
Browser examples
Run each snippet in a fresh browser document. These are static code blocks; ByteMind browser execution is not verified. Storage examples require a test origin.
function decode(raw){try{const x=JSON.parse(raw);return x&&x.v===1&&["light","dark"].includes(x.theme)?x.theme:"light";}catch{return "light";}}console.log(decode('{"v":1,"theme":"dark"}'),decode("bad"),decode('{"v":2,"theme":"dark"}'));Expected console output:
dark light lightOnly the supported version and allowed theme are restored.
const e=new StorageEvent("storage",{key:"theme",oldValue:"light",newValue:"dark"});console.log(e.key,e.oldValue,e.newValue);Expected console output:
theme light darkThe event object exposes the supplied change data; cross-document delivery is a separate behavior.
Common mistake
Do not insert restored strings as HTML. Do not assume JSON.parse validates a schema or that storage is an authoritative cross-tab database.
Practice
Write a preference decoder for a versioned object with theme light or dark. Test missing values, invalid JSON, unexpected types and valid data.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Restore validated state and handle storage changes — Knowledge Check
Apply the concept and predict the browser example behavior.
What should happen after JSON.parse succeeds on stored data?
Does the writing document receive its own storage event for a localStorage write?
What should a preference decoder return for an unsupported schema version?
What is the exact console output in Restore validated state and handle storage changes example 1?
function decode(raw){try{const x=JSON.parse(raw);return x&&x.v===1&&["light","dark"].includes(x.theme)?x.theme:"light";}catch{return "light";}}console.log(decode('{"v":1,"theme":"dark"}'),decode("bad"),decode('{"v":2,"theme":"dark"}'));What is the exact console output in Restore validated state and handle storage changes example 2?
const e=new StorageEvent("storage",{key:"theme",oldValue:"light",newValue:"dark"});console.log(e.key,e.oldValue,e.newValue);