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:
Arnaud
2026-07-12 19:06:54 +02:00
parent 5a9e306357
commit e78c959c49
@@ -1,13 +1,34 @@
"use client";
import { useState } from "react";
import { useState, useEffect } from "react";
import { Bell, BellOff } from "lucide-react";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
export function PushSubscribeButton() {
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() {
if (Notification.permission === "denied") {