Sync the cart to an already-logged-in device, not just at login
Cross-device sync only ever worked one way (local→server on every change via CartSync) plus a server→local merge at the exact moment of login/register — a customer already signed in on a second device (no fresh login action happening) never picked up changes made elsewhere. Adds pullServerCart(): idempotent (server qty overwrites a matching local line rather than adding to it, safe to call repeatedly, unlike mergeServerCartIntoLocal()'s additive merge which only stays correct right after a login clears the local cart's ambiguity). Triggered on CartSync's mount and on window focus — covers "open the site while already logged in" and "switch back to this tab after changing the cart on another device," without a polling interval.
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useCart } from "../lib/cart";
|
||||
import { useCart, pullServerCart } from "../lib/cart";
|
||||
|
||||
// Mirrors the local cart to the server whenever it changes, so a logged-in
|
||||
// customer's cart follows them across devices (see Customers.ts's `cart`
|
||||
@@ -10,6 +10,14 @@ import { useCart } from "../lib/cart";
|
||||
// no-op when logged out — POST /api/account/cart 401s in that case, which
|
||||
// this component doesn't need to distinguish from success; there's simply
|
||||
// nothing to keep in sync yet.
|
||||
//
|
||||
// Push (local→server) and pull (server→local) are both handled here, but
|
||||
// deliberately asymmetric: push reacts to every local cart change (that's
|
||||
// this device's news to share), pull only runs on mount and on window
|
||||
// focus (see pullServerCart()'s own comment on why it's safe to call
|
||||
// repeatedly) — no polling interval, since "another device changed my
|
||||
// cart while this tab has been open and unfocused the whole time" is a
|
||||
// rare enough case not to justify a persistent timer.
|
||||
export function CartSync() {
|
||||
const cart = useCart();
|
||||
const isFirstRender = useRef(true);
|
||||
@@ -34,5 +42,11 @@ export function CartSync() {
|
||||
return () => clearTimeout(timeout);
|
||||
}, [cart]);
|
||||
|
||||
useEffect(() => {
|
||||
pullServerCart();
|
||||
window.addEventListener("focus", pullServerCart);
|
||||
return () => window.removeEventListener("focus", pullServerCart);
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user