From ad326ae5f4694f89ba2b7f3a156badaa01e3d039 Mon Sep 17 00:00:00 2001 From: Alexander Petkov Date: Sat, 1 Jul 2023 16:23:35 +0300 Subject: [PATCH] notificationClient: Destroy socket connection when window is not in focus --- .../NotificationSnackBar.tsx | 11 +++++++++-- src/service/visibilityApi.ts | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 src/service/visibilityApi.ts diff --git a/src/components/client/layout/NotificationSnackBar/NotificationSnackBar.tsx b/src/components/client/layout/NotificationSnackBar/NotificationSnackBar.tsx index e57af26a6..9815a593c 100644 --- a/src/components/client/layout/NotificationSnackBar/NotificationSnackBar.tsx +++ b/src/components/client/layout/NotificationSnackBar/NotificationSnackBar.tsx @@ -9,6 +9,7 @@ import { import DonationNotificationLayout from './DonationNotificationLayout' import { NotificationLayoutData } from 'components/client/layout/NotificationSnackBar/DonationNotificationLayout' import notificationClient from 'common/util/notificationClient' +import { useIsWindowInFocus } from 'service/visibilityApi' function NotificationSnackBar({ mainProps, @@ -19,9 +20,15 @@ function NotificationSnackBar({ }) { const [open, setOpen] = useState(true) const [notifications, setNotifications] = useState([]) + const isWindowInFocus = useIsWindowInFocus() useEffect(() => { - if (!notificationClient.connected) notificationClient.connect() + console.log(isWindowInFocus) + if (isWindowInFocus && !notificationClient.connected) notificationClient.connect() + if (!isWindowInFocus && notificationClient.connected) { + notificationClient.disconnect() + return + } notificationClient.on('successfulDonation', (notificationData: NotificationLayoutData) => { setNotifications((prevState) => [...prevState, notificationData]) }) @@ -29,7 +36,7 @@ function NotificationSnackBar({ return () => { notificationClient.off('successfulDonation') } - }, []) + }, [isWindowInFocus]) const handleSnackBarClose = ( _event: React.SyntheticEvent | Event, diff --git a/src/service/visibilityApi.ts b/src/service/visibilityApi.ts new file mode 100644 index 000000000..2a4abffee --- /dev/null +++ b/src/service/visibilityApi.ts @@ -0,0 +1,18 @@ +import { useState, useEffect } from 'react' +export function useIsWindowInFocus() { + const [isWindowInFocus, setIsWindowInFocus] = useState(true) + + function handleVisibilityChange() { + setIsWindowInFocus(!document.hidden) + } + + useEffect(() => { + document.addEventListener('visibilitychange', handleVisibilityChange) + + return () => { + document.removeEventListener('visibilitychange', handleVisibilityChange) + } + }, []) + + return isWindowInFocus +}