From 994a07f4af13dd8bd56e3f87318876ff72c96343 Mon Sep 17 00:00:00 2001 From: pac7 <47831526-pac7@users.noreply.replit.com> Date: Wed, 8 Oct 2025 12:44:37 +0000 Subject: [PATCH] Update user authentication to correctly track previous email addresses Replaces `previousEmail` state with a ref (`previousEmailRef`) to accurately track the user's old email address during authentication flow, specifically for handling email change notifications. Replit-Commit-Author: Agent Replit-Commit-Session-Id: a16cce43-1d93-4e5c-a1e6-6ca90e68cc4f Replit-Commit-Checkpoint-Type: full_checkpoint --- src/hooks/useAuth.tsx | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/hooks/useAuth.tsx b/src/hooks/useAuth.tsx index 54609196..f0f3fff2 100644 --- a/src/hooks/useAuth.tsx +++ b/src/hooks/useAuth.tsx @@ -23,12 +23,12 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const [profile, setProfile] = useState(null); const [loading, setLoading] = useState(true); const [pendingEmail, setPendingEmail] = useState(null); - const [previousEmail, setPreviousEmail] = useState(null); // Refs for lifecycle and cleanup management const isMountedRef = useRef(true); const profileFetchTimeoutRef = useRef(null); const novuUpdateTimeoutRef = useRef(null); + const previousEmailRef = useRef(null); const fetchProfile = async (userId: string) => { try { @@ -107,9 +107,9 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { // Detect confirmed email change: email changed AND no longer pending if ( session?.user && - previousEmail && + previousEmailRef.current && currentEmail && - currentEmail !== previousEmail && + currentEmail !== previousEmailRef.current && !newEmailPending ) { // Clear any existing Novu update timeout @@ -118,6 +118,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { } // Defer Novu update and notifications to avoid blocking auth + const oldEmail = previousEmailRef.current; novuUpdateTimeoutRef.current = setTimeout(async () => { if (!isMountedRef.current) return; @@ -137,7 +138,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { target_user_id: session.user.id, action: 'email_change_completed', details: { - old_email: previousEmail, + old_email: oldEmail, new_email: currentEmail, timestamp: new Date().toISOString(), }, @@ -149,7 +150,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { workflowId: 'email-changed', subscriberId: session.user.id, payload: { - oldEmail: previousEmail, + oldEmail: oldEmail, newEmail: currentEmail, timestamp: new Date().toISOString(), }, @@ -165,7 +166,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { // Update tracked email if (currentEmail) { - setPreviousEmail(currentEmail); + previousEmailRef.current = currentEmail; } if (session?.user) {