From 7baeb94003f0a81c3242ab5c6eb4cd2914d139a3 Mon Sep 17 00:00:00 2001 From: Arnas Donauskas Date: Wed, 1 Jul 2026 11:16:54 +0300 Subject: [PATCH] fix(settings): preserve WhatsApp credential drafts on tab refocus The WhatsApp settings load effect re-ran fetchConfig() whenever `user` or `profileLoading` changed. Supabase's onAuthStateChange fires a token refresh (new `user` object, profileLoading toggles) when the browser tab regains focus, so returning to the tab re-hydrated the form and overwrote any unsaved credential input. Guard the effect with a ref tracking the account id already loaded, so it only fetches once per account and ignores auth-state churn that doesn't actually change the account. Explicit reloads after save, registration verification, and reset still call fetchConfig directly. Closes #307 Co-Authored-By: Claude Opus 4.8 --- src/components/settings/whatsapp-config.tsx | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/components/settings/whatsapp-config.tsx b/src/components/settings/whatsapp-config.tsx index e6e4023..de77125 100644 --- a/src/components/settings/whatsapp-config.tsx +++ b/src/components/settings/whatsapp-config.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useEffect, useState, useCallback } from 'react'; +import { useEffect, useRef, useState, useCallback } from 'react'; import { toast } from 'sonner'; import { Eye, @@ -53,6 +53,13 @@ export function WhatsAppConfig() { const [connectionStatus, setConnectionStatus] = useState('unknown'); const [resetReason, setResetReason] = useState(null); const [statusMessage, setStatusMessage] = useState(''); + // Guards against re-hydrating the form when the load effect below + // re-runs for reasons unrelated to actually switching accounts — + // e.g. Supabase's onAuthStateChange fires a token refresh (new + // `user` object, profileLoading flips true/false) when the browser + // tab regains focus. Without this, that churn calls fetchConfig() + // again and overwrites whatever the user typed but hadn't saved yet. + const loadedAccountIdRef = useRef(null); const [phoneNumberId, setPhoneNumberId] = useState(''); const [wabaId, setWabaId] = useState(''); @@ -164,9 +171,12 @@ export function WhatsAppConfig() { // once the profile arrives. if (authLoading || profileLoading) return; if (!user || !accountId) { + loadedAccountIdRef.current = null; setLoading(false); return; } + if (loadedAccountIdRef.current === accountId) return; + loadedAccountIdRef.current = accountId; fetchConfig(accountId); }, [authLoading, profileLoading, user, accountId, fetchConfig]);