Persist state with localStorage
Serialize records, validate loaded data, and recover from corrupt storage.
- Difficulty
- beginner
- Time
- 40 minutes
- Last verified
- 9/21/2026
What you will build
Serialize records, validate loaded data, and recover from corrupt storage.
Understand the idea first
Serialize records, validate loaded data, and recover from corrupt storage.
Build it step by step
const STORAGE_KEY = 'coderung:sessions:v1';
function saveSessions(items) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
}
function loadSessions() {
try {
const value = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '[]');
return Array.isArray(value) ? value : [];
} catch {
return [];
}
}- Open the project from the previous lesson and record its current result.
- Type and run the example, then complete this task: Add and refresh to verify persistence; then inject broken JSON and recover without a crash.
- Change at least one input, predict the result, and verify it.
- Create and repair this lesson's typical failure: LocalStorage stores strings and is not for secrets; treat loaded data as untrusted.
Read the important lines
- Serialize records, validate loaded data, and recover from corrupt storage.
- Read the code as input, processing, and output; point to each part.
- A first successful run is not enough; verify a different input and an edge case.
Common mistakes and what to check
| Symptom | What to check |
|---|---|
| The result differs from the prediction | LocalStorage stores strings and is not for secrets; treat loaded data as untrusted. |
| Nothing changes after refresh | Save the file, verify the script path, and read the first relevant Console error. |
Practice without copying
Add and refresh to verify persistence; then inject broken JSON and recover without a crash.
Check the answer after you try
Rebuild it without copying and explain each decision. Key check: LocalStorage stores strings and is not for secrets; treat loaded data as untrusted.
Completion check
- I produced the required visible result
- I can explain the input, processing, and output
- I tested normal, edge, and failure cases