Refactor NotificationContext to improve notification fetching logic
- Introduced useEffectEvent for handling notification fetching based on authentication and connection status. - Simplified the useEffect dependencies for fetching notifications when the notification center is opened. - Removed unused token from context to streamline the NotificationProvider component.
This commit is contained in:
parent
3ed92a141b
commit
5de4c23a71
@ -3,7 +3,8 @@ import {
|
||||
useState,
|
||||
useContext,
|
||||
useCallback,
|
||||
useEffect
|
||||
useEffect,
|
||||
useEffectEvent
|
||||
} from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { notification, Drawer } from 'antd'
|
||||
@ -19,7 +20,7 @@ const NotificationContext = createContext()
|
||||
const NotificationProvider = ({ children }) => {
|
||||
const [api, contextHolder] = notification.useNotification()
|
||||
const location = useLocation()
|
||||
const { authenticated, token } = useContext(AuthContext)
|
||||
const { authenticated } = useContext(AuthContext)
|
||||
const {
|
||||
showError,
|
||||
fetchNotificationsApi,
|
||||
@ -27,7 +28,8 @@ const NotificationProvider = ({ children }) => {
|
||||
markAllNotificationsAsReadApi,
|
||||
deleteNotificationApi,
|
||||
deleteAllNotificationsApi,
|
||||
registerNotificationListener
|
||||
registerNotificationListener,
|
||||
connected
|
||||
} = useContext(ApiServerContext)
|
||||
|
||||
const [notificationCenterVisible, setNotificationCenterVisible] =
|
||||
@ -58,6 +60,11 @@ const NotificationProvider = ({ children }) => {
|
||||
}
|
||||
}, [authenticated, fetchNotificationsApi, showError])
|
||||
|
||||
const onFetchNotifications = useEffectEvent(() => {
|
||||
if (!authenticated || !connected) return
|
||||
fetchNotifications()
|
||||
})
|
||||
|
||||
const markNotificationAsRead = useCallback(
|
||||
async (notificationId) => {
|
||||
try {
|
||||
@ -112,17 +119,17 @@ const NotificationProvider = ({ children }) => {
|
||||
|
||||
const unreadCount = notifications.filter((n) => !n.read).length
|
||||
|
||||
// Initial load / when we become authenticated and connected
|
||||
useEffect(() => {
|
||||
if (authenticated == true && notificationCenterVisible == true) {
|
||||
fetchNotifications()
|
||||
}
|
||||
}, [authenticated, notificationCenterVisible, fetchNotifications])
|
||||
onFetchNotifications()
|
||||
}, [authenticated, connected])
|
||||
|
||||
// Refresh when the notification center opens
|
||||
useEffect(() => {
|
||||
if (authenticated && token) {
|
||||
fetchNotifications()
|
||||
if (notificationCenterVisible) {
|
||||
onFetchNotifications()
|
||||
}
|
||||
}, [authenticated, token, fetchNotifications])
|
||||
}, [notificationCenterVisible])
|
||||
|
||||
useEffect(() => {
|
||||
setNotificationCenterVisible(false)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user