2022-06-12 21:17:22 +00:00
|
|
|
import { useEffect } from "react";
|
|
|
|
import { atom, useAtom } from "jotai";
|
|
|
|
|
|
|
|
import type { NotificationPayload } from "~/utils/web-push.server";
|
|
|
|
|
|
|
|
export default function useNotifications() {
|
|
|
|
const [notificationData, setNotificationData] = useAtom(notificationDataAtom);
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-06-19 15:57:51 +00:00
|
|
|
const eventSource = new EventSource("/sse/notifications");
|
|
|
|
eventSource.addEventListener("message", onMessage);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
eventSource.removeEventListener("message", onMessage);
|
|
|
|
eventSource.close();
|
|
|
|
};
|
|
|
|
|
|
|
|
function onMessage(event: MessageEvent) {
|
|
|
|
console.log("event.data", JSON.parse(event.data));
|
|
|
|
const notifyChannel = new BroadcastChannel("notifications");
|
|
|
|
notifyChannel.postMessage(event.data);
|
|
|
|
notifyChannel.close();
|
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const notifyChannel = new BroadcastChannel("notifications");
|
2022-06-12 21:17:22 +00:00
|
|
|
async function eventHandler(event: MessageEvent) {
|
|
|
|
const payload: NotificationPayload = JSON.parse(event.data);
|
|
|
|
setNotificationData(payload);
|
|
|
|
}
|
|
|
|
|
2022-06-19 15:57:51 +00:00
|
|
|
notifyChannel.addEventListener("message", eventHandler);
|
2022-06-12 21:17:22 +00:00
|
|
|
|
|
|
|
return () => {
|
2022-06-19 15:57:51 +00:00
|
|
|
notifyChannel.removeEventListener("message", eventHandler);
|
|
|
|
notifyChannel.close();
|
2022-06-12 21:17:22 +00:00
|
|
|
};
|
2022-06-14 23:28:32 +00:00
|
|
|
}, [setNotificationData]);
|
2022-06-12 21:17:22 +00:00
|
|
|
|
|
|
|
useEffect(() => {
|
2022-06-19 15:57:51 +00:00
|
|
|
if (!notificationData || notificationData.data.type === "call") {
|
2022-06-12 21:17:22 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const timeout = setTimeout(() => setNotificationData(null), 5000);
|
|
|
|
return () => clearTimeout(timeout);
|
2022-06-14 23:28:32 +00:00
|
|
|
}, [notificationData, setNotificationData]);
|
2022-06-12 21:17:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export const notificationDataAtom = atom<NotificationPayload | null>(null);
|