diff --git a/hooks/use-courrier.ts b/hooks/use-courrier.ts index aa00d98b..b9cdc8d8 100644 --- a/hooks/use-courrier.ts +++ b/hooks/use-courrier.ts @@ -368,19 +368,107 @@ export const useCourrier = () => { console.log(`[changeFolder] Setting currentFolder to: ${prefixedFolder}`); setCurrentFolder(prefixedFolder); - // CRITICAL FIX: Wait for state updates to propagate - setTimeout(async () => { + // CRITICAL FIX: Create a local implementation of loadEmails that doesn't use currentFolder state + // This completely avoids the race condition with React state updates + const loadEmailsForFolder = async () => { try { - // CRITICAL FIX: Always pass the effective account ID explicitly to loadEmails - // This ensures account context is maintained even if currentFolder hasn't updated yet - await loadEmails(false, effectiveAccountId); + console.log(`[changeFolder] Loading emails with fixed parameters: folder=${normalizedFolder}, accountId=${effectiveAccountId}`); + + // CRITICAL FIX: Use a timeout to give UI time to update but avoid state race conditions + await new Promise(resolve => setTimeout(resolve, 50)); + + setIsLoading(true); + setError(null); + + // Try to get cached emails first with the correct parameters + // This uses our local variables, not the potentially stale state + const cachedEmails = await getCachedEmailsWithTimeout( + session?.user?.id || '', // userId + `${effectiveAccountId}:${normalizedFolder}`, // folderForCache - use local variables + 1, // page + perPage, // perPage + 100, // timeoutMs + effectiveAccountId // accountId - use local variable + ); + + if (cachedEmails) { + // Process cached emails similar to loadEmails + if (Array.isArray(cachedEmails.emails)) { + // Set emails from cache using the local function + console.log(`[changeFolder] Setting ${cachedEmails.emails.length} cached emails for folder ${normalizedFolder}`); + setEmails(cachedEmails.emails.sort((a: Email, b: Email) => + new Date(b.date).getTime() - new Date(a.date).getTime())); + + // Set other state from cache + if (cachedEmails.totalEmails) setTotalEmails(cachedEmails.totalEmails); + if (cachedEmails.totalPages) setTotalPages(cachedEmails.totalPages); + if (cachedEmails.mailboxes && cachedEmails.mailboxes.length > 0) { + setMailboxes(cachedEmails.mailboxes); + } + } + + // Start background refresh with the correct parameters + console.log(`[changeFolder] Starting background refresh with folder=${normalizedFolder}, accountId=${effectiveAccountId}`); + refreshEmailsInBackground( + session?.user?.id || '', + normalizedFolder, // Use normalized folder name without prefix + 1, // page + perPage, // perPage + effectiveAccountId // Use effective account ID + ).catch(err => { + console.error('[changeFolder] Background refresh error:', err); + }); + } else { + // No cache hit, perform direct API call similar to loadEmails + // Construct query parameters with the correct values + const queryParams = new URLSearchParams({ + folder: normalizedFolder, + page: '1', + perPage: perPage.toString(), + accountId: effectiveAccountId + }); + + console.log(`[changeFolder] Fetching emails from API with params: ${queryParams.toString()}`); + const response = await fetch(`/api/courrier?${queryParams.toString()}`); + + if (!response.ok) { + const errorData = await response.json(); + throw new Error(errorData.error || 'Failed to fetch emails'); + } + + const data = await response.json(); + + // Update state with fetched data + if (Array.isArray(data.emails)) { + setEmails(data.emails.sort((a: Email, b: Email) => + new Date(b.date).getTime() - new Date(a.date).getTime())); + + if (data.totalEmails) setTotalEmails(data.totalEmails); + if (data.totalPages) setTotalPages(data.totalPages); + if (data.mailboxes && data.mailboxes.length > 0) { + setMailboxes(data.mailboxes); + } + } else { + setEmails([]); + } + } + console.log(`[changeFolder] Finished changing to folder=${prefixedFolder}`); + } catch (error) { - console.error(`[changeFolder] Error in delayed loadEmails:`, error); + console.error(`[changeFolder] Error loading emails:`, error); setError(error instanceof Error ? error.message : 'Error loading emails'); + } finally { setIsLoading(false); } - }, 50); + }; + + // Execute our local function that doesn't depend on state updates + loadEmailsForFolder().catch(error => { + console.error(`[changeFolder] Unhandled error:`, error); + setError(error instanceof Error ? error.message : 'Unknown error'); + setIsLoading(false); + }); } catch (error) { console.error(`[changeFolder] Error changing to folder ${folder}:`, error); setError(error instanceof Error ? error.message : 'Unknown error');