diff --git a/app/components/NotificationHandler.js b/app/components/NotificationHandler.js index 9afd2e3..0dd3068 100644 --- a/app/components/NotificationHandler.js +++ b/app/components/NotificationHandler.js @@ -1,33 +1,44 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useState, useRef } from "react"; import { requestNotificationPermission, onForegroundMessage } from "../utils/firebase"; import AuthService from "../services/AuthService"; export default function NotificationHandler() { const [notification, setNotification] = useState(null); - const [unsubscribe, setUnsubscribe] = useState(null); + const initialized = useRef(false); useEffect(() => { - const user = AuthService.getUser(); - if (!user) return; + // Wait for hydration to complete + const timer = setTimeout(() => { + if (initialized.current) return; + initialized.current = true; - // User is signed in — request permission and listen for messages - requestNotificationPermission().then((token) => { - if (token) { - console.log("[Notifications] FCM token obtained"); + const token = AuthService.getToken(); + if (!token) { + console.log("[Notifications] Not signed in, skipping"); + return; } - }); - const unsub = onForegroundMessage((payload) => { - const title = payload.notification?.title || payload.data?.title || "Sweet Home"; - const body = payload.notification?.body || payload.data?.body || ""; - setNotification({ title, body }); - setTimeout(() => setNotification(null), 5000); - }); + console.log("[Notifications] Signed in, requesting permission..."); + requestNotificationPermission().then((fcmToken) => { + if (fcmToken) { + console.log("[Notifications] FCM token obtained:", fcmToken.substring(0, 20) + "..."); + } + }); - setUnsubscribe(() => unsub); - return () => unsub(); + const unsub = onForegroundMessage((payload) => { + const title = payload.notification?.title || payload.data?.title || "Sweet Home"; + const body = payload.notification?.body || payload.data?.body || ""; + setNotification({ title, body }); + setTimeout(() => setNotification(null), 5000); + }); + + // Cleanup on unmount + return () => unsub(); + }, 1000); // Wait 1s for hydration + + return () => clearTimeout(timer); }, []); if (!notification) return null;