CodingNic

Persist the Wishlist and Load Saved Movies

Load the Wishlist from localStorage

Persist the Wishlist and Load Saved Movies 10 min read

Load the Wishlist from localStorage

Load the Wishlist from localStorage

Restore the saved movie ids when the browser becomes available. The provider should start empty, read from storage once, and then announce that it is ready.

Step 1 — Define the storage key

At the top of context/WishlistContext.tsx, add one constant so all storage access uses the same name.

typescript
const STORAGE_KEY = "matinee-wishlist";

Step 2 — Read after mount

Inside the provider, add an effect that accesses window.localStorage. This must happen after the component mounts because window is a browser object.

typescript
useEffect(() => {
  try {
    const stored = window.localStorage.getItem(STORAGE_KEY);

When a stored value exists, parse it and pass the ids into state. Finish the effect by setting ready to true.

typescript
if (stored) setIds(JSON.parse(stored));

Step 3 — Protect the read

Wrap the storage read in try/catch. If the stored value is corrupted or storage is unavailable, start with an empty list instead of breaking the whole application.

Checkpoint

Save one movie, refresh the browser, and confirm that the heart is still filled. The context should report ready = true after the initial read completes.