32 lines
1.0 KiB
TypeScript
32 lines
1.0 KiB
TypeScript
import { usePage } from '@inertiajs/react';
|
|
import { useEffect, useRef } from 'react';
|
|
import { usePushNotification } from '@/hooks/use-push-notification';
|
|
|
|
export function NotificationPermissionPrompt() {
|
|
const { vapidPublicKey } = usePage().props as { vapidPublicKey?: string };
|
|
const hasRequested = useRef(false);
|
|
|
|
const { isSupported, requestPermission, subscribe } =
|
|
usePushNotification();
|
|
|
|
useEffect(() => {
|
|
if (!isSupported || hasRequested.current || !vapidPublicKey) {
|
|
return;
|
|
}
|
|
|
|
hasRequested.current = true;
|
|
|
|
if (Notification.permission === 'default') {
|
|
void requestPermission().then(async (result) => {
|
|
if (result === 'granted') {
|
|
await subscribe(vapidPublicKey);
|
|
}
|
|
});
|
|
} else if (Notification.permission === 'granted') {
|
|
void subscribe(vapidPublicKey);
|
|
}
|
|
}, [isSupported, requestPermission, subscribe, vapidPublicKey]);
|
|
|
|
return null;
|
|
}
|