notify of incoming messages and show in app notifications

This commit is contained in:
m5r
2022-06-12 23:17:22 +02:00
parent a77f02189e
commit ceaadc4f99
7 changed files with 268 additions and 44 deletions

View File

@ -0,0 +1,34 @@
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(() => {
const channel = new BroadcastChannel("notifications");
async function eventHandler(event: MessageEvent) {
const payload: NotificationPayload = JSON.parse(event.data);
setNotificationData(payload);
}
channel.addEventListener("message", eventHandler);
return () => {
channel.removeEventListener("message", eventHandler);
channel.close();
};
}, []);
useEffect(() => {
if (!notificationData) {
return;
}
const timeout = setTimeout(() => setNotificationData(null), 5000);
return () => clearTimeout(timeout);
}, [notificationData]);
}
export const notificationDataAtom = atom<NotificationPayload | null>(null);