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

View File

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