-
Notifications
You must be signed in to change notification settings - Fork 585
/
Copy pathuse-notifications.ts
45 lines (39 loc) · 1.14 KB
/
use-notifications.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import {RouterError, trpcReact} from '@/trpc/trpc'
/**
* Hook to query and clear system notifications
*/
export function useNotifications() {
const utils = trpcReact.useContext()
// Query to fetch notifications
const {
data: notifications = [],
isLoading,
isError,
error,
} = trpcReact.notifications.get.useQuery(undefined, {
keepPreviousData: true,
onError: (error: RouterError) => {
console.error('Failed to fetch notifications:', error)
},
})
// Mutation to clear a notification
const clearNotification = trpcReact.notifications.clear.useMutation({
onMutate: async (notificationToRemove: string) => {
await utils.notifications.get.cancel()
const previousNotifications = utils.notifications.get.getData()
// Optimistically update the notifications list
utils.notifications.get.setData(undefined, (old = []) => old.filter((n) => n !== notificationToRemove))
return {previousNotifications}
},
onSettled: () => {
utils.notifications.get.invalidate()
},
})
return {
notifications,
clearNotification: (notification: string) => clearNotification.mutate(notification),
isLoading,
isError,
error,
}
}