From 5de4c23a7195aee43c24abca2982bf0757ae5df4 Mon Sep 17 00:00:00 2001 From: Tom Butcher Date: Mon, 10 Aug 2026 23:29:49 +0100 Subject: [PATCH] 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. --- .../Dashboard/context/NotificationContext.jsx | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/src/components/Dashboard/context/NotificationContext.jsx b/src/components/Dashboard/context/NotificationContext.jsx index 5e15bbb..75a24c8 100644 --- a/src/components/Dashboard/context/NotificationContext.jsx +++ b/src/components/Dashboard/context/NotificationContext.jsx @@ -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)