localStorage is not defined.
Likely cause: Browser storage was accessed on the server or at module initialization.
Check and correct: Keep the read inside the client effect or a function called by that effect.
PROJECT 3 · LESSON 9 OF 18
Restore browser data after hydration and handle corrupt storage.
Continue from lesson 8: Share the cart across routes. Keep existing files; create or replace the complete files listed below.
Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.
Shared state solves disagreement between components, but a full refresh creates a new component tree. Persistence needs a separate storage location and a careful order for restoring and saving data.
localStorage belongs to the browser, even though Client Components can be prerendered on the server. Both initial renders start with an empty cart; an effect restores the stored data after hydration.
The ready flag prevents the initial empty array from overwriting a saved cart. Browser storage is untrusted input, so validate its shape. This cart is per browser, not per account; private saved carts are a later extension.
A Client Component can participate in server prerendering. The server does not have localStorage. The initial browser render must also agree with the server-generated UI for hydration to work predictably. Starting with [] in both places gives them the same initial state.
After hydration, the restoration effect can read localStorage in the browser. It replaces lines with validated stored data and sets ready to true. The cart page uses ready to show Restoring cart rather than briefly telling the shopper their saved cart is empty.
The persistence effect also runs after a render. Without the ready check, it could save the initial empty array before restoration has completed, destroying the previous cart. With the gate, the first save is skipped. Once restored state and ready are committed, the effect writes the restored or subsequently updated lines.
JSON.stringify serializes the array into a storage string. JSON.parse reconstructs a value, but that value is not necessarily a valid cart. The reader checks for an array, unique string IDs, integer quantities and the allowed range. A malformed JSON string is caught and treated as an empty cart.
localStorage is scoped to the website origin and browser profile. It is not associated with a signed-in account. A different device does not see the same cart. The example also does not subscribe to storage events, so two open tabs do not synchronize their in-memory views automatically.
Storage can fail because of browser settings or capacity. The catch blocks allow shopping to continue in memory. A production UI could explain that saving is unavailable, but a storage exception should not crash the entire storefront.
The ready guard also prevents AddToCart from racing with restoration. If a shopper added an item before the saved state arrived, a later restore could overwrite the new choice. Disable that operation until the initial restore finishes.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
Server and initial browser render use an empty cart with ready=false.
The browser effect reads and validates saved JSON.
The provider commits restored lines and ready=true.
Later line changes trigger the save effect, which writes the new array.
The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.
This is the single owner of shared client cart state and its permitted operations.
"use client";
import {
createContext,
useContext,
useEffect,
useState,
type ReactNode,
} from "react";
import { changeQuantity, type CartLine } from "@/lib/cart";
type Cart = {
lines: CartLine[];
ready: boolean;
setQuantity: (id: string, n: number) => void;
add: (id: string) => void;
clear: () => void;
};
const Context = createContext<Cart | null>(null);
const KEY = "edushop-cart-v1";
function readCart(): CartLine[] {
try {
const value: unknown = JSON.parse(localStorage.getItem(KEY) ?? "[]");
if (!Array.isArray(value)) return [];
const seen = new Set<string>();
return value
.filter((line): line is CartLine => {
if (
!line ||
typeof line.productId !== "string" ||
!Number.isInteger(line.quantity) ||
line.quantity < 1 ||
line.quantity > 10 ||
seen.has(line.productId)
)
return false;
seen.add(line.productId);
return true;
})
.slice(0, 50);
} catch {
return [];
}
}
export function CartProvider({ children }: { children: ReactNode }) {
const [lines, setLines] = useState<CartLine[]>([]);
const [ready, setReady] = useState(false);
useEffect(() => {
// Synchronize browser storage after hydration; never read it during SSR.
setLines(readCart());
setReady(true);
}, []);
useEffect(() => {
if (ready) {
try {
localStorage.setItem(KEY, JSON.stringify(lines));
} catch {
/* Cart still works in memory. */
}
}
}, [lines, ready]);
function setQuantity(id: string, n: number) {
if (ready && Number.isFinite(n))
setLines((old) => changeQuantity(old, id, n));
}
function add(id: string) {
if (ready)
setLines((old) =>
changeQuantity(
old,
id,
(old.find((l) => l.productId === id)?.quantity ?? 0) + 1,
),
);
}
return (
<Context.Provider
value={{ lines, ready, setQuantity, add, clear: () => setLines([]) }}
>
{children}
</Context.Provider>
);
}
export function useCart() {
const value = useContext(Context);
if (!value) throw new Error("CartProvider is missing");
return value;
}
This gives a product card a small client-side control without moving the whole catalog into client state.
"use client";
import { useCart } from "./cart-provider";
export default function AddToCart({ id }: { id: string }) {
const { add, ready } = useCart();
return (
<button disabled={!ready} onClick={() => add(id)}>
Add to cart
</button>
);
}
This renders cart choices and derives their display values from the catalog.
"use client";
import { products } from "@/lib/products";
import { money } from "@/lib/money";
import { useCart } from "@/components/cart-provider";
export default function CartPage() {
const { lines, ready, setQuantity, clear } = useCart();
if (!ready) return <p>Restoring cart…</p>;
const total = lines.reduce(
(sum, line) =>
sum +
(products.find((p) => p.id === line.productId)?.price ?? 0) *
line.quantity,
0,
);
return (
<>
<h1>Your cart</h1>
{lines.map((line) => {
const product = products.find((p) => p.id === line.productId);
return (
<article key={line.productId}>
<h2>{product?.name ?? "Unavailable product"}</h2>
<label>
Quantity{" "}
<input
type="number"
min="1"
max="10"
value={line.quantity}
onChange={(e) => {
const n = Number(e.target.value);
if (Number.isInteger(n) && n > 0)
setQuantity(line.productId, n);
}}
/>
</label>
<p>{money((product?.price ?? 0) * line.quantity)}</p>
<button onClick={() => setQuantity(line.productId, 0)}>
Remove
</button>
</article>
);
})}
{!lines.length && (
<p>Your cart is empty. Visit Products to add an item.</p>
)}
<p>Total: {money(total)}</p>
{!!lines.length && <button onClick={clear}>Clear cart</button>}
</>
);
}
In browser storage, set the quantity to -4 or create two p1 entries. Reload and inspect the cart.
Invalid quantities are rejected and duplicate product IDs do not become duplicate cart lines.
Parsing JSON checks syntax only. Runtime validation checks whether the data is acceptable for this application.
Do not read localStorage at module scope or save the initial empty cart before restoration finishes.
Likely cause: Browser storage was accessed on the server or at module initialization.
Check and correct: Keep the read inside the client effect or a function called by that effect.
Likely cause: The initial empty state was persisted before restoration.
Check and correct: Keep the ready gate around saving and disable add operations until restoration completes.
Add a message explaining that the guest cart is saved on this device.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
The component may render on the server, where that API is unavailable. A browser-only initializer can also create an initial hydration mismatch.
No. The shopper controls browser storage. Checkout must validate quantities and retrieve authoritative prices and stock on the server.