fix: push-notification toggle in settings always showed as off
Never checked the browser's actual push subscription on mount — state initialized to false unconditionally, so the button looked reset to "Enable notifications" on every page load even when notifications were genuinely still active. Now checks navigator.serviceWorker + getSubscription() on mount and initializes from that.
This commit is contained in:
@@ -1,13 +1,34 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { Bell, BellOff } from "lucide-react";
|
import { Bell, BellOff } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
export function PushSubscribeButton() {
|
export function PushSubscribeButton() {
|
||||||
const [subscribed, setSubscribed] = useState(false);
|
const [subscribed, setSubscribed] = useState(false);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
// The button previously always started as "not subscribed" regardless of
|
||||||
|
// actual state — it never checked the browser's real push subscription on
|
||||||
|
// mount, so it looked reset every time this page loaded even when
|
||||||
|
// notifications were genuinely still enabled.
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
if (!("serviceWorker" in navigator)) return;
|
||||||
|
const registration = await navigator.serviceWorker.ready;
|
||||||
|
const sub = await registration.pushManager.getSubscription();
|
||||||
|
if (!cancelled) setSubscribed(!!sub);
|
||||||
|
} catch {
|
||||||
|
// ignore — leave as not-subscribed if the check itself fails
|
||||||
|
} finally {
|
||||||
|
if (!cancelled) setLoading(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
async function handleSubscribe() {
|
async function handleSubscribe() {
|
||||||
if (Notification.permission === "denied") {
|
if (Notification.permission === "denied") {
|
||||||
|
|||||||
Reference in New Issue
Block a user