MCPcopy Create free account
hub / github.com/dailydotdev/apps / useInAppNotification

Function useInAppNotification

packages/shared/src/hooks/useInAppNotification.ts:37–109  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

35
36const queue: NewNotification[] = [];
37export const useInAppNotification = (): UseInAppNotification => {
38 const client = useQueryClient();
39 const { incrementUnreadCount } = useNotificationContext();
40 const { data: notification } = useQuery<InAppNotification>({
41 queryKey: IN_APP_NOTIFICATION_KEY,
42
43 queryFn: () =>
44 client.getQueryData<InAppNotification>(IN_APP_NOTIFICATION_KEY) || null,
45 });
46 const hasNotification = (): boolean =>
47 !!client.getQueryData(IN_APP_NOTIFICATION_KEY);
48 const setInAppNotification = (data: InAppNotification) =>
49 client.setQueryData(IN_APP_NOTIFICATION_KEY, data);
50
51 const displayNotification = (
52 payload: NewNotification,
53 { timer = 5000 }: NotifyOptionalProps = {},
54 ) => {
55 setInAppNotification({ notification: payload, timer });
56 };
57
58 const addToQueue = (newNotification: NewNotification) => {
59 if (!newNotification || registeredNotification[newNotification.id]) {
60 return;
61 }
62
63 registeredNotification[newNotification.id] = true;
64 incrementUnreadCount();
65 queue.push(newNotification);
66 if (queue.length >= MAX_QUEUE_LENGTH) {
67 queue.shift();
68 }
69 if (!hasNotification()) {
70 displayNotification(queue.shift());
71 }
72 };
73
74 const dismissNotification = () => {
75 if (queue.length) {
76 displayNotification(queue.shift());
77 return;
78 }
79 setInAppNotification(null);
80 };
81
82 const clearNotifications = () => {
83 queue.length = 0;
84 dismissNotification();
85 };
86
87 useSubscription(
88 () => ({
89 query: NEW_NOTIFICATIONS_SUBSCRIPTION,
90 }),
91 {
92 next: ({ newNotification }: PushNotificationSubscription) => {
93 addToQueue(newNotification);
94 },

Callers 1

InAppNotificationElementFunction · 0.90

Calls 3

useNotificationContextFunction · 0.90
useSubscriptionFunction · 0.85
addToQueueFunction · 0.85

Tested by

no test coverage detected