1.6 KiB
1.6 KiB
Quickstart: Persist Encounter
What This Feature Does
Saves the current encounter to browser localStorage so it survives page reloads. No user action required -- saving and restoring happens automatically.
Key Files
| File | Purpose |
|---|---|
apps/web/src/persistence/encounter-storage.ts |
New: read/write/validate encounter in localStorage |
apps/web/src/hooks/use-encounter.ts |
Modified: load from storage on init, persist on change |
How It Works
- On app load: The
useEncounterhook callsloadEncounter()from the storage module. If valid data exists, it initializes state from it. Otherwise, the demo encounter is used. - On every state change: A
useEffectwatches the encounter state and callssaveEncounter()to write it to localStorage. - On error: All storage operations are wrapped in try/catch. Failures are silent -- the app continues working in memory-only mode.
Testing
pnpm vitest run apps/web/src/persistence/__tests__/encounter-storage.test.ts
Tests cover:
- Round-trip serialization (save then load returns same encounter)
- Invalid/corrupt data returns null
- Missing fields return null
- Non-JSON data returns null
Manual Verification
- Run
pnpm --filter web dev - Add/remove combatants, set initiative, advance turns
- Refresh the page -- encounter state should be preserved
- Open DevTools > Application > localStorage to inspect the stored data
- Delete the storage key and refresh -- demo encounter should appear
- Set the storage value to
"garbage"and refresh -- demo encounter should appear