Neah/hooks/use-mail.ts
2025-04-17 14:32:49 +02:00

48 lines
1.4 KiB
TypeScript

import { useState, useCallback } from 'react';
import type { Mail } from '@/types/mail';
export type { Mail };
export const useMail = () => {
const [mails, setMails] = useState<Mail[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const fetchMails = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const response = await fetch('/api/mail');
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to fetch mails');
}
const data = await response.json();
// Map the API response to our Mail interface
const formattedMails = data.map((mail: any) => ({
id: mail.id.toString(),
from: mail.from,
to: '', // Will be populated when viewing individual mail
subject: mail.subject || '(No subject)',
body: '', // Will be populated when viewing individual mail
date: new Date(mail.date).toISOString(),
read: false, // Default to unread
starred: false, // Default to not starred
folder: 'INBOX', // Default to INBOX
}));
setMails(formattedMails);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch mails');
setMails([]);
} finally {
setIsLoading(false);
}
}, []);
return {
mails,
isLoading,
error,
fetchMails,
};
};