diff --git a/app/courrier/page.tsx b/app/courrier/page.tsx index 6ef56338..e0820d22 100644 --- a/app/courrier/page.tsx +++ b/app/courrier/page.tsx @@ -141,11 +141,21 @@ export default function CourrierPage() { useEffect(() => { // Flag to prevent multiple initialization attempts let isMounted = true; + let initAttempted = false; const initSession = async () => { + if (initAttempted) return; + initAttempted = true; + try { + setLoading(true); + // First check if Redis is ready before making API calls - const redisStatus = await fetch('/api/redis/status').then(res => res.json()).catch(() => null); + const redisStatus = await fetch('/api/redis/status') + .then(res => res.json()) + .catch(() => ({ ready: false })); + + if (!isMounted) return; // Call the session API to check email credentials and start prefetching const response = await fetch('/api/courrier/session'); @@ -153,29 +163,52 @@ export default function CourrierPage() { if (!isMounted) return; - if (data.authenticated && data.hasEmailCredentials) { - console.log('Session initialized, prefetching started'); - setPrefetchStarted(true); - - // Preload first page of emails for faster initial rendering - if (session?.user?.id) { - loadEmails(); + if (data.authenticated) { + if (data.hasEmailCredentials) { + console.log('Session initialized, prefetch status:', data.prefetchStarted ? 'running' : 'not started'); + setPrefetchStarted(Boolean(data.prefetchStarted)); + + // Preload first page of emails for faster initial rendering + if (session?.user?.id) { + await loadEmails(); + + // If the user hasn't opened this page recently, trigger a background refresh + if (data.lastVisit && Date.now() - data.lastVisit > 5 * 60 * 1000) { + // It's been more than 5 minutes, refresh in background + try { + const refreshResponse = await fetch('/api/courrier/refresh', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ folder: currentFolder }) + }); + console.log('Background refresh triggered'); + } catch (error) { + console.error('Failed to trigger background refresh', error); + } + } + } + } else { + // User is authenticated but doesn't have email credentials + setShowLoginNeeded(true); } - } else if (data.authenticated && !data.hasEmailCredentials) { - // User is authenticated but doesn't have email credentials - setShowLoginNeeded(true); } } catch (error) { console.error('Error initializing session:', error); + } finally { + if (isMounted) { + setLoading(false); + } } }; - initSession(); + if (session?.user?.id) { + initSession(); + } return () => { isMounted = false; }; - }, [session?.user?.id, loadEmails]); + }, [session?.user?.id, loadEmails, currentFolder]); // Helper to get folder icons const getFolderIcon = (folder: string) => {