106 lines
2.9 KiB
TypeScript
106 lines
2.9 KiB
TypeScript
import { useState, useEffect, useCallback } from 'react'
|
|
import { notificationService } from '@/lib/notificationService'
|
|
import type { Notification } from '@/lib/notificationService'
|
|
|
|
export function useNotifications(userPubkey: string | null): {
|
|
notifications: Notification[]
|
|
unreadCount: number
|
|
loading: boolean
|
|
markAsRead: (notificationId: string) => void
|
|
markAllAsRead: () => void
|
|
deleteNotification: (notificationId: string) => void
|
|
} {
|
|
const [notifications, setNotifications] = useState<Notification[]>([])
|
|
const [loading, setLoading] = useState(true)
|
|
|
|
// Load stored notifications on mount and refresh periodically
|
|
useEffect(() => {
|
|
if (!userPubkey) {
|
|
setNotifications([])
|
|
setLoading(false)
|
|
return
|
|
}
|
|
|
|
const loadNotifications = async (): Promise<void> => {
|
|
try {
|
|
setLoading(true)
|
|
const storedNotifications = await notificationService.getAllNotifications(100)
|
|
setNotifications(storedNotifications)
|
|
} catch (error) {
|
|
console.error('[useNotifications] Error loading notifications:', error)
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}
|
|
|
|
void loadNotifications()
|
|
|
|
// Refresh notifications every 30 seconds
|
|
const interval = setInterval(() => {
|
|
void loadNotifications()
|
|
}, 30000)
|
|
|
|
return () => {
|
|
clearInterval(interval)
|
|
}
|
|
}, [userPubkey])
|
|
|
|
const unreadCount = notifications.filter((n) => !n.read).length
|
|
|
|
const markAsRead = useCallback(
|
|
async (notificationId: string): Promise<void> => {
|
|
if (!userPubkey) {
|
|
return
|
|
}
|
|
|
|
try {
|
|
await notificationService.markAsRead(notificationId)
|
|
setNotifications((prev) =>
|
|
prev.map((n) => (n.id === notificationId ? { ...n, read: true } : n))
|
|
)
|
|
} catch (error) {
|
|
console.error('[useNotifications] Error marking notification as read:', error)
|
|
}
|
|
},
|
|
[userPubkey]
|
|
)
|
|
|
|
const markAllAsReadHandler = useCallback(async (): Promise<void> => {
|
|
if (!userPubkey) {
|
|
return
|
|
}
|
|
|
|
try {
|
|
await notificationService.markAllAsRead()
|
|
setNotifications((prev) => prev.map((n) => ({ ...n, read: true })))
|
|
} catch (error) {
|
|
console.error('[useNotifications] Error marking all as read:', error)
|
|
}
|
|
}, [userPubkey])
|
|
|
|
const deleteNotificationHandler = useCallback(
|
|
async (notificationId: string): Promise<void> => {
|
|
if (!userPubkey) {
|
|
return
|
|
}
|
|
|
|
try {
|
|
await notificationService.deleteNotification(notificationId)
|
|
setNotifications((prev) => prev.filter((n) => n.id !== notificationId))
|
|
} catch (error) {
|
|
console.error('[useNotifications] Error deleting notification:', error)
|
|
}
|
|
},
|
|
[userPubkey]
|
|
)
|
|
|
|
return {
|
|
notifications,
|
|
unreadCount,
|
|
loading,
|
|
markAsRead,
|
|
markAllAsRead: markAllAsReadHandler,
|
|
deleteNotification: deleteNotificationHandler,
|
|
}
|
|
}
|