From 67c4f9f435fc93871b29a9589ebdab695b02cdf8 Mon Sep 17 00:00:00 2001 From: Oluwatoyin Solomon Date: Mon, 17 Aug 2026 19:15:10 +0100 Subject: [PATCH] fix(frontend): eliminate profile hydration drift and harden stored metadata Renders public profile pages, header navigation, and countdown widgets deterministically on server and client so users no longer see flicker, hydration mismatches, or stale content across refreshes. Stored profile metadata is now validated and merged safely, recovering gracefully from malformed local data. Test infrastructure (pre-existing failures): - vitest.config.ts: remove duplicate setupFiles key (empty array shadowed vitest.setup.ts) so jest-dom matchers load, fixing the SigningSummary failures. - usePersistentState.ts: hold serialize/deserialize in refs so inline (unstable) callback identities no longer re-trigger the hydration effect into an infinite re-render loop; fixed its test (jest -> vi, correct import path). Metadata consistency: - types/profile.ts: add ProfileMetadata, PROFILE_METADATA_DEFAULTS, and sanitizeProfileMetadata (hex color, absolute http(s) avatar URL, trimmed + length-capped bio/handles; never throws). - lib/api.ts: readStoredProfileMetadata + safe merge with per-field sanitization; corrupt/non-object localStorage entries are removed on read; storage keys canonicalized to lowercase in getProfile/saveProfile. - app/[username]/page.tsx: reset state per username change, avatar onError fallback to initial, consistent error copy for invalid/private/not-found states, role=status + role=alert + aria-live. Hydration-safe time/locale rendering: - hooks/marketplaceApi.ts: export standalone formatCountdown(date, now?) mirroring the provider implementations. - components/UsernameCard.tsx: mounted-pattern 'now' state (updated every 30s) replaces Date.now() at render to keep countdown/urgency/UrgencyBar identical between SSR and client. - lib/i18n.ts: init deterministically in 'en' on server and client; components/Header.tsx restores the saved language post-hydration and fixes the leading-space aria-label. Other: - app/manifest.ts: add lang/dir and complete shortcut icon type/purpose metadata. Pre-existing type/build errors fixed so the app compiles: - app/page.tsx: drop dead fetchListings warm-up (import never existed). - app/dashboard/page.tsx: consume fetchUserBids/fetchUserListings via MarketplaceApiProvider + useMarketplaceApi(). - app/marketplace/page.tsx: remove duplicate showWatchlistOnly state and import useRef. - components/PWAHandler.tsx: pass route/extra context to errorReporter (valid ErrorContext). Verification: full vitest suite green (12 files, 105 tests) and tsc --noEmit -p tsconfig.test.json clean. New unit tests cover sanitizeProfileMetadata and api.ts merge/recovery behavior. --- app/frontend/src/app/[username]/page.tsx | 40 +++-- app/frontend/src/app/dashboard/page.tsx | 25 +-- app/frontend/src/app/manifest.ts | 20 ++- app/frontend/src/app/marketplace/page.tsx | 3 +- app/frontend/src/app/page.tsx | 7 - app/frontend/src/components/Header.tsx | 14 +- app/frontend/src/components/PWAHandler.tsx | 2 +- app/frontend/src/components/UsernameCard.tsx | 33 +++- .../__tests__/usePersistentState.test.tsx | 7 +- app/frontend/src/hooks/marketplaceApi.ts | 18 ++ app/frontend/src/hooks/usePersistentState.ts | 22 ++- app/frontend/src/lib/__tests__/api.test.ts | 160 ++++++++++++++++++ app/frontend/src/lib/api.ts | 97 ++++++++--- app/frontend/src/lib/i18n.ts | 9 +- .../src/types/__tests__/profile.test.ts | 106 ++++++++++++ app/frontend/src/types/profile.ts | 125 ++++++++++++++ app/frontend/vitest.config.ts | 1 - 17 files changed, 613 insertions(+), 76 deletions(-) create mode 100644 app/frontend/src/lib/__tests__/api.test.ts create mode 100644 app/frontend/src/types/__tests__/profile.test.ts diff --git a/app/frontend/src/app/[username]/page.tsx b/app/frontend/src/app/[username]/page.tsx index 44400c935..4cf8acc8d 100644 --- a/app/frontend/src/app/[username]/page.tsx +++ b/app/frontend/src/app/[username]/page.tsx @@ -11,6 +11,12 @@ import type { Profile } from "@/types/profile"; const FOCUS_RING_CLASS = "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-300 focus-visible:ring-offset-2 focus-visible:ring-offset-black"; +const ERROR_COPY = { + invalidUsername: "Invalid username", + notFound: "Username not found or profile is private", + fallback: "Failed to load profile", +} as const; + export default function PublicProfile() { const params = useParams(); const router = useRouter(); @@ -19,6 +25,7 @@ export default function PublicProfile() { const [profile, setProfile] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); + const [avatarFailed, setAvatarFailed] = useState(false); const [paymentForm, setPaymentForm] = useState({ amount: "", @@ -29,18 +36,22 @@ export default function PublicProfile() { useEffect(() => { let mounted = true; + // Reset per-username state so navigating between profiles never shows + // stale content (avoids flicker / metadata inconsistency across refreshes). + setProfile(null); + setAvatarFailed(false); + setError(null); + setLoading(true); + async function fetchProfile() { if (!username) { - setError("Invalid username"); + setError(ERROR_COPY.invalidUsername); setLoading(false); return; } try { - setLoading(true); - setError(null); const data = await getProfile(username); - if (mounted) { setProfile(data); } @@ -48,11 +59,11 @@ export default function PublicProfile() { if (!mounted) return; if (err instanceof ProfileNotFoundError) { - setError("Username not found or profile is private"); + setError(ERROR_COPY.notFound); } else if (err instanceof Error) { setError(err.message); } else { - setError("Failed to load profile"); + setError(ERROR_COPY.fallback); } setProfile(null); } finally { @@ -71,7 +82,11 @@ export default function PublicProfile() { if (loading) { return ( -
+

Loading profile...

@@ -82,11 +97,14 @@ export default function PublicProfile() { if (error || !profile) { return ( -
+

404

- {error || "Username not found"} + {error || ERROR_COPY.notFound}