diff --git a/hooks/use-email-state.ts b/hooks/use-email-state.ts index c925f2b4..84b3ea65 100644 --- a/hooks/use-email-state.ts +++ b/hooks/use-email-state.ts @@ -681,36 +681,43 @@ export const useEmailState = () => { // Effect to load emails when folder changes useEffect(() => { if (session?.user?.id && state.currentFolder) { - // Skip if we're in the middle of pagination (handleLoadMore was just called) - if (lastPageLoadedRef.current > 1) { - console.log(`[DEBUG-FOLDER_EFFECT] Skipping folder load because we're in the middle of pagination (page ${state.page}, lastLoaded ${lastPageLoadedRef.current})`); - return; - } - + // CRITICAL FIX: REMOVE this check that's causing the problem + // Instead, detect a real folder change and always load when that happens + // Extract account ID for consistent loading const { effectiveAccountId } = normalizeFolderAndAccount(state.currentFolder); // Track if the folder actually changed const folderChanged = prevFolderRef.current !== state.currentFolder; + if (folderChanged) { console.log(`[DEBUG-FOLDER_EFFECT] Folder changed from ${prevFolderRef.current} to ${state.currentFolder}`); prevFolderRef.current = state.currentFolder; - } - - logEmailOp('FOLDER_CHANGE', `Loading emails for folder ${state.currentFolder} with account ${effectiveAccountId}`); - - // CRITICAL FIX: Only reset page if the folder actually changed - if (folderChanged && state.page !== 1) { - console.log(`[DEBUG-FOLDER_EFFECT] Resetting page to 1 because folder changed`); - dispatch({ type: 'SET_PAGE', payload: 1 }); - // Also reset the lastLoaded tracker + // CRITICAL FIX: Always reset pagination state when folder actually changes + console.log(`[DEBUG-FOLDER_EFFECT] Folder changed - resetting pagination state`); + + // Reset page to 1 AND reset lastPageLoadedRef to ensure we load lastPageLoadedRef.current = 0; + + if (state.page !== 1) { + console.log(`[DEBUG-FOLDER_EFFECT] Resetting page to 1 because folder changed`); + dispatch({ type: 'SET_PAGE', payload: 1 }); + } + + // CRITICAL FIX: Clear emails and set loading when folder changes + dispatch({ type: 'SET_EMAILS', payload: [] }); + dispatch({ type: 'SET_LOADING', payload: true }); + + // CRITICAL FIX: Always load emails when folder changes, no matter what + console.log(`[DEBUG-FOLDER_EFFECT] Loading emails for new folder: ${state.currentFolder}`); + loadEmails(1, state.perPage, false); + return; // Exit early after handling folder change } - // CRITICAL FIX: Only load initial emails if we're on page 1 or the folder changed - if (state.page === 1 || folderChanged) { - // Load emails with the correct account ID (not appending since this is a folder change) + // If no folder change detected, only load if on page 1 and not already loaded + if (state.page === 1 && lastPageLoadedRef.current === 0) { + logEmailOp('FOLDER_LOAD', `Loading initial emails for folder ${state.currentFolder}`); loadEmails(state.page, state.perPage, false); } }