useBrowserNotifications: don't set state if already unmounted.

Closes 1053

We can't cancel a promise, but we could prevent setting orphaned states by taking advantage of closures to detect if we have unmounted.

Reference: https://juliangaramendy.dev/blog/use-promise-subscription
This commit is contained in:
infinite-persistence 2022-03-09 13:00:51 +08:00
parent efbbba6958
commit d210e81ded
No known key found for this signature in database
GPG key ID: B9C3252EDC3D0AA0

View file

@ -20,13 +20,19 @@ export default () => {
useEffect(() => { useEffect(() => {
if (!user) return; if (!user) return;
let mounted = true;
setPushSupported(pushNotifications.supported); setPushSupported(pushNotifications.supported);
if (pushNotifications.supported) { if (pushNotifications.supported) {
pushNotifications.subscribed(user.id).then((isSubscribed: boolean) => { pushNotifications.subscribed(user.id).then((isSubscribed: boolean) => {
if (mounted) {
setSubscribed(isSubscribed); setSubscribed(isSubscribed);
setPushInitialized(true); setPushInitialized(true);
}
}); });
} }
return () => {
mounted = false;
};
}, [user]); }, [user]);
useMemo(() => setPushEnabled(pushPermission === 'granted' && subscribed), [pushPermission, subscribed]); useMemo(() => setPushEnabled(pushPermission === 'granted' && subscribed), [pushPermission, subscribed]);