fix: only request notification permissions for signed-in users
All checks were successful
Build frontend / build (push) Successful in 39s
All checks were successful
Build frontend / build (push) Successful in 39s
This commit is contained in:
@ -2,31 +2,32 @@
|
|||||||
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { requestNotificationPermission, onForegroundMessage } from "../utils/firebase";
|
import { requestNotificationPermission, onForegroundMessage } from "../utils/firebase";
|
||||||
|
import AuthService from "../services/AuthService";
|
||||||
|
|
||||||
export default function NotificationHandler() {
|
export default function NotificationHandler() {
|
||||||
const [notification, setNotification] = useState(null);
|
const [notification, setNotification] = useState(null);
|
||||||
|
const [unsubscribe, setUnsubscribe] = useState(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Request permission and get token
|
const user = AuthService.getUser();
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
|
// User is signed in — request permission and listen for messages
|
||||||
requestNotificationPermission().then((token) => {
|
requestNotificationPermission().then((token) => {
|
||||||
if (token) {
|
if (token) {
|
||||||
console.log("[Notifications] FCM token obtained");
|
console.log("[Notifications] FCM token obtained");
|
||||||
// TODO: Send token to your backend to register the device
|
|
||||||
// e.g. apiFetch('/Notifications/RegisterDevice', { method: 'POST', body: { token } })
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Listen for foreground messages
|
const unsub = onForegroundMessage((payload) => {
|
||||||
const unsubscribe = onForegroundMessage((payload) => {
|
|
||||||
const title = payload.notification?.title || payload.data?.title || "Sweet Home";
|
const title = payload.notification?.title || payload.data?.title || "Sweet Home";
|
||||||
const body = payload.notification?.body || payload.data?.body || "";
|
const body = payload.notification?.body || payload.data?.body || "";
|
||||||
setNotification({ title, body });
|
setNotification({ title, body });
|
||||||
|
|
||||||
// Auto-dismiss after 5 seconds
|
|
||||||
setTimeout(() => setNotification(null), 5000);
|
setTimeout(() => setNotification(null), 5000);
|
||||||
});
|
});
|
||||||
|
|
||||||
return () => unsubscribe();
|
setUnsubscribe(() => unsub);
|
||||||
|
return () => unsub();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
if (!notification) return null;
|
if (!notification) return null;
|
||||||
|
|||||||
Reference in New Issue
Block a user