From f26e41707a8dc4b01ca476487520bf2775b8fbdd Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Mon, 19 May 2025 15:16:50 +0000 Subject: [PATCH] Fix: Instance cards not rendering The commit addresses the issue where instance cards were not appearing after creation. It revisits the `WhatsApp.tsx` file and related components to ensure instances are correctly added to the state and displayed. --- .../whatsapp/CreateInstanceForm.tsx | 2 +- src/hooks/useWhatsAppInstances.ts | 4 +- src/pages/WhatsApp.tsx | 5 +- src/services/whatsAppService.ts | 84 +++++++++++-------- 4 files changed, 57 insertions(+), 38 deletions(-) diff --git a/src/components/whatsapp/CreateInstanceForm.tsx b/src/components/whatsapp/CreateInstanceForm.tsx index d907ddd..3e3eeb3 100644 --- a/src/components/whatsapp/CreateInstanceForm.tsx +++ b/src/components/whatsapp/CreateInstanceForm.tsx @@ -63,7 +63,7 @@ const CreateInstanceForm = ({ onInstanceCreated }: CreateInstanceFormProps) => { // Create new instance object with user ID const newInstance: WhatsAppInstance = { instanceName, - instanceId: data.instance?.instanceId || Date.now().toString(), // Fallback if instanceId not provided + instanceId: data.instance?.instanceId || instanceName, // Use instanceName as fallback ID phoneNumber, userId: currentUserId, // Associate with current user status: data.instance?.status || 'created', diff --git a/src/hooks/useWhatsAppInstances.ts b/src/hooks/useWhatsAppInstances.ts index 30816f8..cedae41 100644 --- a/src/hooks/useWhatsAppInstances.ts +++ b/src/hooks/useWhatsAppInstances.ts @@ -30,7 +30,7 @@ export const useWhatsAppInstances = () => { // Save instances to localStorage whenever they change useEffect(() => { - if (currentUserId) { + if (currentUserId && instances.length > 0) { console.log('Saving instances to localStorage:', instances); saveInstancesToLocalStorage(instances, currentUserId); } @@ -38,6 +38,8 @@ export const useWhatsAppInstances = () => { // Function to check connection status for all instances const checkAllInstancesStatus = async () => { + if (instances.length === 0) return; + try { const updatedInstances = await Promise.all( instances.map(async (instance) => { diff --git a/src/pages/WhatsApp.tsx b/src/pages/WhatsApp.tsx index ed46a18..9ff47b9 100644 --- a/src/pages/WhatsApp.tsx +++ b/src/pages/WhatsApp.tsx @@ -51,10 +51,11 @@ const WhatsApp = () => { clearInterval(interval); } }; - }, [instances.length]); + }, [instances.length, checkAllInstancesStatus]); // Handler for when a new instance is created const handleInstanceCreated = async (newInstance: WhatsAppInstance) => { + console.log('New instance to be added:', newInstance); addInstance(newInstance); // If there's a QR code in the response, show it @@ -74,6 +75,8 @@ const WhatsApp = () => { } }; + console.log('Current instances in WhatsApp component:', instances); + return (
diff --git a/src/services/whatsAppService.ts b/src/services/whatsAppService.ts index d63acff..b073abb 100644 --- a/src/services/whatsAppService.ts +++ b/src/services/whatsAppService.ts @@ -4,6 +4,9 @@ import { WhatsAppInstance } from '@/types/whatsAppTypes'; const SERVER_URL = "evolutionapi2.innova1001.com.br"; const API_KEY = "beeb77fbd7f48f91db2cd539a573c130"; +// Local storage key +const STORAGE_KEY = 'whatsappInstances'; + export const createWhatsAppInstance = async ( instanceName: string, phoneNumber: string @@ -188,48 +191,59 @@ export const saveInstancesToLocalStorage = ( instances: WhatsAppInstance[], currentUserId: string ): void => { - // We need to save ALL instances (not just current user's) to maintain everyone's data - const savedInstances = localStorage.getItem('whatsappInstances'); - let allInstances: WhatsAppInstance[] = []; - - if (savedInstances) { - try { - const parsedInstances = JSON.parse(savedInstances); - // Filter out current user's instances from saved data (we'll add updated ones) - allInstances = parsedInstances.filter( - (instance: WhatsAppInstance) => instance.userId !== currentUserId - ); - } catch (error) { - console.error("Error parsing saved instances:", error); + try { + // Get existing instances from localStorage + const savedInstancesStr = localStorage.getItem(STORAGE_KEY); + let allInstances: WhatsAppInstance[] = []; + + if (savedInstancesStr) { + // Parse saved instances + const savedInstances = JSON.parse(savedInstancesStr); + + // If it's an array, filter out current user's old instances + if (Array.isArray(savedInstances)) { + allInstances = savedInstances.filter( + (instance: WhatsAppInstance) => instance.userId !== currentUserId + ); + } } + + // Add current user's instances to the array + const updatedInstances = [...allInstances, ...instances]; + + // Save back to localStorage + localStorage.setItem(STORAGE_KEY, JSON.stringify(updatedInstances)); + console.log('All WhatsApp instances saved to localStorage:', updatedInstances); + } catch (error) { + console.error('Error saving instances to localStorage:', error); } - - // Add current user's instances to the array - const updatedInstances = [...allInstances, ...instances]; - localStorage.setItem('whatsappInstances', JSON.stringify(updatedInstances)); - console.log('All WhatsApp instances saved to localStorage:', updatedInstances); }; export const loadInstancesFromLocalStorage = ( userId: string ): WhatsAppInstance[] => { - const savedInstances = localStorage.getItem('whatsappInstances'); - console.log('Raw saved instances from localStorage:', savedInstances); - - if (savedInstances && userId) { - try { - const allInstances = JSON.parse(savedInstances); - // Filter instances to only show those belonging to the current user - const userInstances = allInstances.filter( - (instance: WhatsAppInstance) => instance.userId === userId - ); - console.log(`Found ${userInstances.length} instances for user ${userId}:`, userInstances); - return userInstances; - } catch (error) { - console.error("Error parsing saved instances:", error); - return []; + try { + const savedInstancesStr = localStorage.getItem(STORAGE_KEY); + console.log('Raw saved instances from localStorage:', savedInstancesStr); + + if (savedInstancesStr && userId) { + // Parse saved instances + const allInstances = JSON.parse(savedInstancesStr); + + // If it's an array, filter by user ID + if (Array.isArray(allInstances)) { + // Filter instances to only show those belonging to the current user + const userInstances = allInstances.filter( + (instance: WhatsAppInstance) => instance.userId === userId + ); + console.log(`Found ${userInstances.length} instances for user ${userId}:`, userInstances); + return userInstances; + } } + console.log(`No instances found for user ${userId}`); + return []; + } catch (error) { + console.error("Error loading instances from localStorage:", error); + return []; } - console.log(`No instances found for user ${userId}`); - return []; };