Skip to content

Commit

Permalink
notificationClient: Destroy socket connection when window is not in f…
Browse files Browse the repository at this point in the history
…ocus
  • Loading branch information
sashko9807 committed Jul 1, 2023
1 parent 85a80b0 commit ad326ae
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -19,17 +20,23 @@ function NotificationSnackBar({
}) {
const [open, setOpen] = useState(true)
const [notifications, setNotifications] = useState<NotificationLayoutData[]>([])
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])
})

return () => {
notificationClient.off('successfulDonation')
}
}, [])
}, [isWindowInFocus])

const handleSnackBarClose = (
_event: React.SyntheticEvent | Event,
Expand Down
18 changes: 18 additions & 0 deletions src/service/visibilityApi.ts
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit ad326ae

Please sign in to comment.