From 9b988030533d55e55b6918fbec1e9aa5da0cd31f Mon Sep 17 00:00:00 2001 From: Michelle Date: Fri, 13 Mar 2026 12:43:20 +0100 Subject: [PATCH] fix(NotificationContext): handle user ID for notifications fetching and prevent stale responses --- src/contexts/NotificationContext.jsx | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/contexts/NotificationContext.jsx b/src/contexts/NotificationContext.jsx index ba330e5..e4d1fda 100644 --- a/src/contexts/NotificationContext.jsx +++ b/src/contexts/NotificationContext.jsx @@ -49,14 +49,20 @@ export function NotificationProvider({ children }) { const { user } = useAuth(); const [notifications, setNotifications] = useState([]); const [unreadCount, setUnreadCount] = useState(0); + const activeUserId = useRef(null); // Track seen IDs to detect genuinely new arrivals and show toasts const seenIds = useRef(new Set()); const initialized = useRef(false); const fetch = useCallback(async () => { - if (!user) return; + const requestUserId = user?.id; + if (!requestUserId) return; try { const res = await api.get('/notifications'); + + // Ignore stale responses that arrived after logout or account switch. + if (activeUserId.current !== requestUserId) return; + const incoming = res.data.notifications || []; setNotifications(incoming); setUnreadCount(res.data.unreadCount || 0); @@ -106,6 +112,7 @@ export function NotificationProvider({ children }) { }, []); useEffect(() => { + activeUserId.current = user?.id ?? null; if (!user) { setNotifications([]); setUnreadCount(0);