Fix cart quantities doubling on every logout/login and a crash on /cart

Root cause 1 (count doubling): LogoutButton never cleared the local
cart, and mergeServerCartIntoLocal() (called on login) adds server
quantities into the existing local ones rather than replacing — since
CartSync mirrors local to the server continuously, local and server
already held the same quantities at logout time, so every login added
them together, doubling the count each cycle. Fix: clear the local
cart on logout, so the next login's merge starts from empty (or only
genuine guest-session additions) instead of re-adding already-synced
quantities.

Root cause 2 (page couldn't load): readCart()/getCart() only guarded
against JSON.parse syntax errors, not against the parsed value being a
non-array — once localStorage held a corrupted (inflated/malformed)
value, CartContent.tsx's cart.map() threw uncaught during render.
Fix: validate Array.isArray() after parsing, falling back to [].

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Marco
2026-07-30 17:13:54 +00:00
parent 73b4b06eae
commit c6fe65ad99
2 changed files with 20 additions and 5 deletions
+8
View File
@@ -2,12 +2,20 @@
import { useRouter } from "next/navigation";
import { dispatchAuthChanged } from "../../lib/auth";
import { clearCart } from "../../lib/cart";
export function LogoutButton() {
const router = useRouter();
async function handleLogout() {
await fetch("/api/account/logout", { method: "POST" });
// The local cart is already mirrored server-side by CartSync, so it's
// safe to clear it here — the next login's mergeServerCartIntoLocal()
// restores it from the server. Without this, the local cart survived
// logout untouched, and mergeServerCartIntoLocal()'s additive merge
// (existing.qty += qty) would add the already-synced server quantities
// on top of it on every login, doubling every logout/login cycle.
clearCart();
dispatchAuthChanged();
router.push("/");
router.refresh();