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.
This commit is contained in:
gpt-engineer-app[bot] 2025-05-19 15:16:50 +00:00
parent 66a2cc47a8
commit f26e41707a
4 changed files with 57 additions and 38 deletions

View File

@ -63,7 +63,7 @@ const CreateInstanceForm = ({ onInstanceCreated }: CreateInstanceFormProps) => {
// Create new instance object with user ID // Create new instance object with user ID
const newInstance: WhatsAppInstance = { const newInstance: WhatsAppInstance = {
instanceName, instanceName,
instanceId: data.instance?.instanceId || Date.now().toString(), // Fallback if instanceId not provided instanceId: data.instance?.instanceId || instanceName, // Use instanceName as fallback ID
phoneNumber, phoneNumber,
userId: currentUserId, // Associate with current user userId: currentUserId, // Associate with current user
status: data.instance?.status || 'created', status: data.instance?.status || 'created',

View File

@ -30,7 +30,7 @@ export const useWhatsAppInstances = () => {
// Save instances to localStorage whenever they change // Save instances to localStorage whenever they change
useEffect(() => { useEffect(() => {
if (currentUserId) { if (currentUserId && instances.length > 0) {
console.log('Saving instances to localStorage:', instances); console.log('Saving instances to localStorage:', instances);
saveInstancesToLocalStorage(instances, currentUserId); saveInstancesToLocalStorage(instances, currentUserId);
} }
@ -38,6 +38,8 @@ export const useWhatsAppInstances = () => {
// Function to check connection status for all instances // Function to check connection status for all instances
const checkAllInstancesStatus = async () => { const checkAllInstancesStatus = async () => {
if (instances.length === 0) return;
try { try {
const updatedInstances = await Promise.all( const updatedInstances = await Promise.all(
instances.map(async (instance) => { instances.map(async (instance) => {

View File

@ -51,10 +51,11 @@ const WhatsApp = () => {
clearInterval(interval); clearInterval(interval);
} }
}; };
}, [instances.length]); }, [instances.length, checkAllInstancesStatus]);
// Handler for when a new instance is created // Handler for when a new instance is created
const handleInstanceCreated = async (newInstance: WhatsAppInstance) => { const handleInstanceCreated = async (newInstance: WhatsAppInstance) => {
console.log('New instance to be added:', newInstance);
addInstance(newInstance); addInstance(newInstance);
// If there's a QR code in the response, show it // 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 ( return (
<Layout> <Layout>
<div className="space-y-6"> <div className="space-y-6">

View File

@ -4,6 +4,9 @@ import { WhatsAppInstance } from '@/types/whatsAppTypes';
const SERVER_URL = "evolutionapi2.innova1001.com.br"; const SERVER_URL = "evolutionapi2.innova1001.com.br";
const API_KEY = "beeb77fbd7f48f91db2cd539a573c130"; const API_KEY = "beeb77fbd7f48f91db2cd539a573c130";
// Local storage key
const STORAGE_KEY = 'whatsappInstances';
export const createWhatsAppInstance = async ( export const createWhatsAppInstance = async (
instanceName: string, instanceName: string,
phoneNumber: string phoneNumber: string
@ -188,48 +191,59 @@ export const saveInstancesToLocalStorage = (
instances: WhatsAppInstance[], instances: WhatsAppInstance[],
currentUserId: string currentUserId: string
): void => { ): void => {
// We need to save ALL instances (not just current user's) to maintain everyone's data try {
const savedInstances = localStorage.getItem('whatsappInstances'); // Get existing instances from localStorage
const savedInstancesStr = localStorage.getItem(STORAGE_KEY);
let allInstances: WhatsAppInstance[] = []; let allInstances: WhatsAppInstance[] = [];
if (savedInstances) { if (savedInstancesStr) {
try { // Parse saved instances
const parsedInstances = JSON.parse(savedInstances); const savedInstances = JSON.parse(savedInstancesStr);
// Filter out current user's instances from saved data (we'll add updated ones)
allInstances = parsedInstances.filter( // If it's an array, filter out current user's old instances
if (Array.isArray(savedInstances)) {
allInstances = savedInstances.filter(
(instance: WhatsAppInstance) => instance.userId !== currentUserId (instance: WhatsAppInstance) => instance.userId !== currentUserId
); );
} catch (error) {
console.error("Error parsing saved instances:", error);
} }
} }
// Add current user's instances to the array // Add current user's instances to the array
const updatedInstances = [...allInstances, ...instances]; const updatedInstances = [...allInstances, ...instances];
localStorage.setItem('whatsappInstances', JSON.stringify(updatedInstances));
// Save back to localStorage
localStorage.setItem(STORAGE_KEY, JSON.stringify(updatedInstances));
console.log('All WhatsApp instances saved to localStorage:', updatedInstances); console.log('All WhatsApp instances saved to localStorage:', updatedInstances);
} catch (error) {
console.error('Error saving instances to localStorage:', error);
}
}; };
export const loadInstancesFromLocalStorage = ( export const loadInstancesFromLocalStorage = (
userId: string userId: string
): WhatsAppInstance[] => { ): WhatsAppInstance[] => {
const savedInstances = localStorage.getItem('whatsappInstances');
console.log('Raw saved instances from localStorage:', savedInstances);
if (savedInstances && userId) {
try { try {
const allInstances = JSON.parse(savedInstances); 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 // Filter instances to only show those belonging to the current user
const userInstances = allInstances.filter( const userInstances = allInstances.filter(
(instance: WhatsAppInstance) => instance.userId === userId (instance: WhatsAppInstance) => instance.userId === userId
); );
console.log(`Found ${userInstances.length} instances for user ${userId}:`, userInstances); console.log(`Found ${userInstances.length} instances for user ${userId}:`, userInstances);
return userInstances; return userInstances;
} catch (error) {
console.error("Error parsing saved instances:", error);
return [];
} }
} }
console.log(`No instances found for user ${userId}`); console.log(`No instances found for user ${userId}`);
return []; return [];
} catch (error) {
console.error("Error loading instances from localStorage:", error);
return [];
}
}; };