bolt.diy/app/lib/hooks/useNotifications.ts

52 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-01-20 08:53:15 +00:00
import { useState, useEffect } from 'react';
import { getNotifications, markNotificationRead, type Notification } from '~/lib/api/notifications';
2025-01-21 10:55:26 +00:00
import { logStore } from '~/lib/stores/logs';
import { useStore } from '@nanostores/react';
2025-01-20 08:53:15 +00:00
export const useNotifications = () => {
const [hasUnreadNotifications, setHasUnreadNotifications] = useState(false);
const [unreadNotifications, setUnreadNotifications] = useState<Notification[]>([]);
2025-01-21 10:55:26 +00:00
const logs = useStore(logStore.logs);
2025-01-20 08:53:15 +00:00
const checkNotifications = async () => {
try {
const notifications = await getNotifications();
2025-01-21 10:55:26 +00:00
const unread = notifications.filter((n) => !logStore.isRead(n.id));
2025-01-20 08:53:15 +00:00
setUnreadNotifications(unread);
setHasUnreadNotifications(unread.length > 0);
} catch (error) {
console.error('Failed to check notifications:', error);
}
};
useEffect(() => {
// Check immediately and then every minute
checkNotifications();
const interval = setInterval(checkNotifications, 60 * 1000);
return () => clearInterval(interval);
2025-01-21 10:55:26 +00:00
}, [logs]); // Re-run when logs change
2025-01-20 08:53:15 +00:00
const markAsRead = async (notificationId: string) => {
try {
await markNotificationRead(notificationId);
2025-01-21 10:55:26 +00:00
await checkNotifications();
2025-01-20 08:53:15 +00:00
} catch (error) {
console.error('Failed to mark notification as read:', error);
}
};
const markAllAsRead = async () => {
try {
2025-01-21 10:55:26 +00:00
const notifications = await getNotifications();
await Promise.all(notifications.map((n) => markNotificationRead(n.id)));
await checkNotifications();
2025-01-20 08:53:15 +00:00
} catch (error) {
console.error('Failed to mark all notifications as read:', error);
}
};
return { hasUnreadNotifications, unreadNotifications, markAsRead, markAllAsRead };
};