From cd677d17363427ad5f9c6a3752ea70fea2612c18 Mon Sep 17 00:00:00 2001 From: alma Date: Wed, 30 Apr 2025 17:48:09 +0200 Subject: [PATCH] courrier formatting --- hooks/use-email-state.ts | 118 ++++++++++++++++++++++++--------------- 1 file changed, 74 insertions(+), 44 deletions(-) diff --git a/hooks/use-email-state.ts b/hooks/use-email-state.ts index 9e9aed07..94f767b9 100644 --- a/hooks/use-email-state.ts +++ b/hooks/use-email-state.ts @@ -65,6 +65,9 @@ export const useEmailState = () => { const loadEmails = useCallback(async (isLoadMore = false, accountId?: string) => { if (!session?.user?.id) return; + // CRITICAL FIX: Always log the isLoadMore parameter + console.log(`[DEBUG-LOAD_EMAILS] Called with isLoadMore=${isLoadMore}, page=${state.page}, currentEmails=${state.emails.length}`); + dispatch({ type: 'SET_LOADING', payload: true }); try { @@ -99,11 +102,14 @@ export const useEmailState = () => { ); if (cachedEmails) { - logEmailOp('CACHE_HIT', `Using cached data for ${prefixedFolder}, page: ${state.page}, emails: ${cachedEmails.emails?.length || 0}`); + logEmailOp('CACHE_HIT', `Using cached data for ${prefixedFolder}, page: ${state.page}, emails: ${cachedEmails.emails?.length || 0}, isLoadMore: ${isLoadMore}`); // Ensure cached data has emails array property if (Array.isArray(cachedEmails.emails)) { - // Dispatch appropriate action based on if we're loading more + // CRITICAL FIX: Double check we're using the right action type based on isLoadMore param + console.log(`[DEBUG-CACHE_HIT] Dispatching ${isLoadMore ? 'APPEND_EMAILS' : 'SET_EMAILS'} with ${cachedEmails.emails.length} emails`); + + // Dispatch appropriate action based on if we're loading more - DO NOT OVERRIDE isLoadMore! dispatch({ type: isLoadMore ? 'APPEND_EMAILS' : 'SET_EMAILS', payload: cachedEmails.emails @@ -124,28 +130,18 @@ export const useEmailState = () => { } } - // CRITICAL FIX: Completely disable the background refresh mechanism - // This was causing an infinite loop of refreshes and network requests - // Now we'll only fetch new emails when the user explicitly requests them - /* - // Still refresh in background for fresh data - logEmailOp('BACKGROUND_REFRESH', `Starting background refresh for ${prefixedFolder}`); - refreshEmailsInBackground( - session.user.id, - normalizedFolder, - state.page, - state.perPage, - effectiveAccountId - ).catch(err => { - console.error('Background refresh error:', err); - }); - */ + // CRITICAL FIX: If this was a loadMore operation, check the result after the dispatch + if (isLoadMore) { + setTimeout(() => { + console.log(`[DEBUG-CACHE_HIT_APPEND] After ${isLoadMore ? 'APPEND' : 'SET'}, email count is now: ${state.emails.length}`); + }, 0); + } return; } // Fetch emails from API if no cache hit - logEmailOp('API_FETCH', `Fetching emails from API: ${queryParams.toString()}`); + logEmailOp('API_FETCH', `Fetching emails from API: ${queryParams.toString()}, isLoadMore: ${isLoadMore}`); console.log(`[DEBUG-API_FETCH] Fetching from /api/courrier?${queryParams.toString()}`); const response = await fetch(`/api/courrier?${queryParams.toString()}`); @@ -237,6 +233,9 @@ export const useEmailState = () => { }); } + // CRITICAL FIX: Log what we're about to do + console.log(`[DEBUG-DISPATCH] About to dispatch ${isLoadMore ? 'APPEND_EMAILS' : 'SET_EMAILS'} with ${data.emails?.length || 0} emails`); + // Update state with fetched data dispatch({ type: isLoadMore ? 'APPEND_EMAILS' : 'SET_EMAILS', @@ -673,28 +672,63 @@ export const useEmailState = () => { const nextPage = state.page + 1; console.log(`[DEBUG-LOAD_MORE] Incrementing page from ${state.page} to ${nextPage}, current emails count: ${state.emails.length}`); - // Increment the page to trigger the useEffect + // CRITICAL FIX: First set loading state to true to prevent other effects from firing + dispatch({ type: 'SET_LOADING', payload: true }); + + // CRITICAL FIX: Get folder info for consistency + const { effectiveAccountId } = normalizeFolderAndAccount(state.currentFolder); + + // CRITICAL FIX: Directly call loadEmails with isLoadMore=true instead of relying on the useEffect + // This bypasses the issues with the folder change effect interfering + console.log(`[DEBUG-LOAD_MORE] Directly calling loadEmails with isLoadMore=true, page=${nextPage}`); + + // We need to set the page number first, so loadEmails uses the right page dispatch({ type: 'SET_PAGE', payload: nextPage }); - // CRITICAL FIX: Force loading state to true immediately - dispatch({ type: 'SET_LOADING', payload: true }); - }, [state.page, state.totalPages, state.isLoading, state.emails.length, logEmailOp, dispatch]); + // CRITICAL FIX: Update the lastPageLoaded ref to prevent duplicate loading + lastPageLoadedRef.current = nextPage; + + // Now load the emails with the new page number + setTimeout(() => { + loadEmails(true, effectiveAccountId); + }, 0); + }, [state.page, state.totalPages, state.isLoading, state.emails.length, state.currentFolder, logEmailOp, dispatch, loadEmails]); // Effect to load emails when folder changes useEffect(() => { if (session?.user?.id && state.currentFolder) { - // Extract account ID from folder for consistent loading + // 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; + } + + // 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}`); - // Reset page to 1 when changing folders - if (state.page !== 1) { + // 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 + lastPageLoadedRef.current = 0; } - // Load emails with the correct account ID (not appending since this is a folder change) - loadEmails(false, effectiveAccountId); + // 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) + loadEmails(false, effectiveAccountId); + } } }, [session?.user?.id, state.currentFolder, state.page, loadEmails, logEmailOp, dispatch]); @@ -712,34 +746,30 @@ export const useEmailState = () => { return; } - // Debug log - console.log(`[DEBUG-PAGE_EFFECT] Page effect running for page ${state.page}, lastLoaded=${lastPageLoadedRef.current}, current emails count: ${state.emails.length}`); + // CRITICAL FIX: Get current folder data + const { effectiveAccountId, prefixedFolder } = normalizeFolderAndAccount(state.currentFolder); - // Skip if this page was already loaded - if (lastPageLoadedRef.current === state.page) { - console.log(`[DEBUG-PAGE_EFFECT] Skipping reload of already loaded page ${state.page}`); + // Debug log + console.log(`[DEBUG-PAGE_EFFECT] Page changed to ${state.page}, lastLoaded=${lastPageLoadedRef.current}, folder=${prefixedFolder}, emails=${state.emails.length}`); + + // Skip if this page was already loaded for this folder + if (lastPageLoadedRef.current === state.page && prevFolderRef.current === state.currentFolder) { + console.log(`[DEBUG-PAGE_EFFECT] Skipping reload of already loaded page ${state.page} for folder ${prefixedFolder}`); return; } // CRITICAL FIX: Set the ref immediately to prevent further executions lastPageLoadedRef.current = state.page; - // Extract account ID for consistency - const { effectiveAccountId } = normalizeFolderAndAccount(state.currentFolder); + // Make sure we also track the current folder + prevFolderRef.current = state.currentFolder; - logEmailOp('PAGINATION', `Loading more emails for page ${state.page} (total emails so far: ${state.emails.length})`); + logEmailOp('PAGINATION', `Loading MORE emails for page ${state.page} for folder ${prefixedFolder} (total emails so far: ${state.emails.length})`); // CRITICAL FIX: Always use isLoadMore=true when page > 1 + console.log(`[DEBUG-PAGE_EFFECT] Calling loadEmails with isLoadMore=true for page ${state.page}`); loadEmails(true, effectiveAccountId); - // Reset the lastPageLoadedRef when folder changes or component unmounts - return () => { - if (state.currentFolder !== prevFolderRef.current) { - console.log(`[DEBUG-PAGE_EFFECT] Folder changed from ${prevFolderRef.current} to ${state.currentFolder}, resetting lastPageLoaded`); - lastPageLoadedRef.current = 0; - prevFolderRef.current = state.currentFolder; - } - }; // Do NOT include state.emails.length here to prevent infinite loops }, [session?.user?.id, state.page, state.currentFolder, state.isLoading, loadEmails, logEmailOp]);