Fix: WhatsApp instance search trigger

The instance search was incorrectly triggered on every keystroke in the instance name input field. The fix ensures that the search uses the saved instance name from local storage, and is only triggered when the "Conectar WhatsApp" menu is opened. The instance name input field is now only used for creating new instances.
This commit is contained in:
gpt-engineer-app[bot] 2025-05-20 16:57:16 +00:00
parent 12e6cda1df
commit 62e2acbf4e
2 changed files with 28 additions and 25 deletions

View File

@ -12,13 +12,11 @@ import { WhatsAppInstance } from '@/types/whatsAppTypes';
interface CreateInstanceFormProps { interface CreateInstanceFormProps {
onInstanceCreated: (instance: WhatsAppInstance) => void; onInstanceCreated: (instance: WhatsAppInstance) => void;
initialInstanceName?: string; initialInstanceName?: string;
onInstanceNameChange?: (name: string) => void;
} }
const CreateInstanceForm = ({ const CreateInstanceForm = ({
onInstanceCreated, onInstanceCreated,
initialInstanceName = '', initialInstanceName = ''
onInstanceNameChange
}: CreateInstanceFormProps) => { }: CreateInstanceFormProps) => {
const { toast } = useToast(); const { toast } = useToast();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@ -33,14 +31,6 @@ const CreateInstanceForm = ({
} }
}, [initialInstanceName]); }, [initialInstanceName]);
const handleInstanceNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newName = e.target.value;
setInstanceName(newName);
if (onInstanceNameChange) {
onInstanceNameChange(newName);
}
};
const handleCreateInstance = async () => { const handleCreateInstance = async () => {
// Validate form fields // Validate form fields
if (!instanceName.trim()) { if (!instanceName.trim()) {
@ -101,7 +91,6 @@ const CreateInstanceForm = ({
}); });
// Reset form fields // Reset form fields
setInstanceName(localStorage.getItem('userName') || '');
setPhoneNumber(''); setPhoneNumber('');
} catch (error) { } catch (error) {
@ -133,7 +122,7 @@ const CreateInstanceForm = ({
<Input <Input
id="instanceName" id="instanceName"
value={instanceName} value={instanceName}
onChange={handleInstanceNameChange} onChange={(e) => setInstanceName(e.target.value)}
placeholder="Digite um nome para a instância" placeholder="Digite um nome para a instância"
required required
/> />

View File

@ -11,6 +11,8 @@ import { useWhatsAppActions } from '@/hooks/useWhatsAppActions';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
import { fetchSpecificInstance } from '@/services/whatsApp/instanceManagement'; import { fetchSpecificInstance } from '@/services/whatsApp/instanceManagement';
const WHATSAPP_INSTANCE_KEY = 'whatsapp_instance_name';
const WhatsApp = () => { const WhatsApp = () => {
const { toast } = useToast(); const { toast } = useToast();
const { const {
@ -34,10 +36,15 @@ const WhatsApp = () => {
handleViewQrCode handleViewQrCode
} = useWhatsAppActions(updateInstance, removeInstance, checkAllInstancesStatus); } = useWhatsAppActions(updateInstance, removeInstance, checkAllInstancesStatus);
// Obter o nome da instância salvo no localStorage
const [instanceName, setInstanceName] = useState(() => { const [instanceName, setInstanceName] = useState(() => {
// Get user's name from localStorage as default instance name const userId = localStorage.getItem('userId');
return localStorage.getItem('userName') || ''; if (userId) {
return localStorage.getItem(`${WHATSAPP_INSTANCE_KEY}_${userId}`) || '';
}
return '';
}); });
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [instanceFound, setInstanceFound] = useState(false); const [instanceFound, setInstanceFound] = useState(false);
const currentUserId = localStorage.getItem('userId') || ''; const currentUserId = localStorage.getItem('userId') || '';
@ -122,7 +129,7 @@ const WhatsApp = () => {
}; };
}, [instances.length, checkAllInstancesStatus]); }, [instances.length, checkAllInstancesStatus]);
// Fetch the specific instance when the component mounts // Fetch the specific instance when the component mounts (não a cada digitação)
useEffect(() => { useEffect(() => {
if (currentUserId) { if (currentUserId) {
fetchInstanceByName(); fetchInstanceByName();
@ -133,19 +140,20 @@ const WhatsApp = () => {
variant: "destructive" variant: "destructive"
}); });
} }
}, [currentUserId, instanceName]); }, [currentUserId]);
// Handler for when the user changes the instance name // Handler para quando o usuário cria uma nova instância
const handleInstanceNameChange = (name: string) => { const handleInstanceCreated = (newInstance: WhatsAppInstance) => {
setInstanceName(name);
};
// Handler for when a new instance is created
const handleInstanceCreated = async (newInstance: WhatsAppInstance) => {
console.log('New instance to be added:', newInstance); console.log('New instance to be added:', newInstance);
addInstance(newInstance); addInstance(newInstance);
setInstanceFound(true); setInstanceFound(true);
// Salvar o nome da instância no localStorage para uso futuro
if (currentUserId) {
localStorage.setItem(`${WHATSAPP_INSTANCE_KEY}_${currentUserId}`, newInstance.instanceName);
setInstanceName(newInstance.instanceName);
}
// If there's a QR code in the response, show it // If there's a QR code in the response, show it
if (newInstance.qrcode) { if (newInstance.qrcode) {
handleViewQrCode(newInstance); handleViewQrCode(newInstance);
@ -172,6 +180,13 @@ const WhatsApp = () => {
const instanceToDelete = instances.find(i => i.instanceId === instanceId); const instanceToDelete = instances.find(i => i.instanceId === instanceId);
if (instanceToDelete) { if (instanceToDelete) {
handleDeleteInstance(instanceId, instanceToDelete.instanceName); handleDeleteInstance(instanceId, instanceToDelete.instanceName);
// Se a instância excluída for a atual, limpar o nome salvo
if (instanceToDelete.instanceName === instanceName && currentUserId) {
localStorage.removeItem(`${WHATSAPP_INSTANCE_KEY}_${currentUserId}`);
setInstanceName('');
setInstanceFound(false);
}
} else { } else {
console.error(`Instance with ID ${instanceId} not found for deletion`); console.error(`Instance with ID ${instanceId} not found for deletion`);
toast({ toast({
@ -202,7 +217,6 @@ const WhatsApp = () => {
<CreateInstanceForm <CreateInstanceForm
onInstanceCreated={handleInstanceCreated} onInstanceCreated={handleInstanceCreated}
initialInstanceName={instanceName} initialInstanceName={instanceName}
onInstanceNameChange={handleInstanceNameChange}
/> />
) : ( ) : (
// Only show stats and instance list if instance found // Only show stats and instance list if instance found