diff --git a/components/mobile/profile/ThemeSessionBridge.tsx b/components/mobile/profile/ThemeSessionBridge.tsx index 5e5b3c4..7d00531 100644 --- a/components/mobile/profile/ThemeSessionBridge.tsx +++ b/components/mobile/profile/ThemeSessionBridge.tsx @@ -10,7 +10,7 @@ * Renders nothing. */ -import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; import { useTheme } from 'next-themes'; import { useSession } from '@/lib/auth-client'; @@ -19,8 +19,15 @@ type SessionUserWithTheme = { theme?: 'light' | 'dark' | 'system' | string }; export function ThemeSessionBridge() { const { data: session } = useSession(); const { theme, setTheme } = useTheme(); + // Sync server → client EXACTLY ONCE per tab session. better-auth's + // useSession (nanostores) can re-emit on focus / store refresh, which would + // otherwise call setTheme with the stale cached session.user.theme and + // revert the user's just-made selection. The PUT to /api/me/theme does NOT + // refresh the cached session, so any post-selection re-fire would clobber. + const hasSynced = useRef(false); useEffect(() => { + if (hasSynced.current) return; if (!session?.user) return; const serverTheme = (session.user as SessionUserWithTheme).theme; // Only enforce explicit choices. 'system' is the column default and may @@ -32,12 +39,7 @@ export function ThemeSessionBridge() { setTheme(serverTheme); } } - // Deps intentionally exclude `theme`. This bridge syncs server → client - // on session establishment only. Including `theme` made the effect re-fire - // on every user selection and revert to the stale cached - // `session.user.theme` (the PUT to /api/me/theme does not refresh the - // better-auth session, so user.theme remains the pre-change value and - // "wins" against the new client value). + hasSynced.current = true; // eslint-disable-next-line react-hooks/exhaustive-deps }, [session?.user?.id, setTheme]);