Neah/hooks/use-email-fetch.ts

139 lines
4.2 KiB
TypeScript

import { useState, useEffect, useCallback, useRef } from 'react';
import { useToast } from './use-toast';
interface EmailFetchState {
email: any | null;
loading: boolean;
error: string | null;
}
interface UseEmailFetchProps {
onEmailLoaded?: (email: any) => void;
onError?: (error: string) => void;
}
export function useEmailFetch({ onEmailLoaded, onError }: UseEmailFetchProps = {}) {
const [state, setState] = useState<EmailFetchState>({
email: null,
loading: false,
error: null
});
const abortControllerRef = useRef<AbortController | null>(null);
const { toast } = useToast();
// Validate email fetch parameters
const validateFetchParams = (emailId: string, accountId: string, folder: string) => {
if (!emailId || typeof emailId !== 'string') {
throw new Error('Invalid email ID');
}
if (!accountId || typeof accountId !== 'string') {
throw new Error('Invalid account ID');
}
if (!folder || typeof folder !== 'string') {
throw new Error('Invalid folder');
}
// Validate UID format
if (!/^\d+$/.test(emailId)) {
throw new Error('Email ID must be a numeric UID');
}
};
// Fetch email with proper error handling and cancellation
const fetchEmail = useCallback(async (emailId: string, accountId: string, folder: string) => {
if (!emailId || !accountId || !folder) {
console.error('Missing required parameters for fetchEmail');
return;
}
// CRITICAL FIX: Always abort any previous request when fetching a new email
// This prevents race conditions when switching accounts or folders
if (abortControllerRef.current) {
console.log(`useEmailFetch: Aborting previous request to fetch email ${emailId} from account ${accountId}`);
abortControllerRef.current.abort();
}
// Create a new abort controller for this request
abortControllerRef.current = new AbortController();
setState(prev => ({ ...prev, loading: true, error: null }));
try {
console.log('useEmailFetch: Fetching email with params:', { emailId, accountId, folder });
const response = await fetch(
`/api/courrier/${emailId}?accountId=${encodeURIComponent(accountId)}&folder=${encodeURIComponent(folder)}`,
{
signal: abortControllerRef.current?.signal
}
);
if (!response.ok) {
throw new Error(`Failed to fetch email: ${response.statusText}`);
}
const data = await response.json();
console.log('useEmailFetch: Raw API response:', JSON.stringify(data, null, 2));
// Transform the data if needed
const transformedEmail = {
...data,
content: data.content || {
text: data.text || '',
html: data.html || ''
}
};
console.log('useEmailFetch: Transformed email:', JSON.stringify(transformedEmail, null, 2));
setState({ email: transformedEmail, loading: false, error: null });
onEmailLoaded?.(transformedEmail);
// Mark as read if not already
if (!transformedEmail.flags?.seen) {
try {
await fetch(`/api/courrier/${emailId}/mark-read`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'mark-read' })
});
} catch (err) {
console.error('Error marking email as read:', err);
}
}
} catch (err) {
// Don't set error if request was aborted
if (err.name === 'AbortError') {
return;
}
console.error('useEmailFetch: Error fetching email:', err);
const errorMessage = err instanceof Error ? err.message : 'Failed to load email';
setState(prev => ({ ...prev, loading: false, error: errorMessage }));
onError?.(errorMessage);
// Show toast for user feedback
toast({
title: 'Error',
description: errorMessage,
variant: 'destructive'
});
}
}, [onEmailLoaded, onError, toast]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
};
}, []);
return {
...state,
fetchEmail
};
}