From 4ca7ecbb6a2a8de27aa427d18440191e6e056b32 Mon Sep 17 00:00:00 2001 From: Tom Butcher Date: Sun, 23 Aug 2026 21:45:04 +0100 Subject: [PATCH] Refactor Reconnection Logic in ApiServerContext - Introduced a new function to handle reconnection attempts when the socket is disconnected, improving the robustness of the connection management. - Updated the visibility change and window focus event handlers to utilize the new reconnection logic, ensuring better handling of socket states during user interactions. - Enhanced the subscription management for activity listeners when the page becomes visible, improving responsiveness and user experience. --- .../Dashboard/context/ApiServerContext.jsx | 38 +++++++++++++------ 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/src/components/Dashboard/context/ApiServerContext.jsx b/src/components/Dashboard/context/ApiServerContext.jsx index 80a3c615..0826ba5f 100644 --- a/src/components/Dashboard/context/ApiServerContext.jsx +++ b/src/components/Dashboard/context/ApiServerContext.jsx @@ -603,29 +603,43 @@ const ApiServerProvider = ({ children }) => { }, [token, authenticated, connectionIssue, scheduleReconnect]) useEffect(() => { + const reconnectIfDisconnected = (reason) => { + if (!token || authenticated !== true) { + return false + } + + const socket = socketRef.current + if (socket?.connected) { + return false + } + + logger.debug(`${reason} with disconnected socket, reconnecting...`) + reconnectAttemptRef.current = 0 + attemptReconnect() + return true + } + const handlePageVisible = () => { if (document.visibilityState !== 'visible') { return } + if (reconnectIfDisconnected('Page visible')) { + return + } + const socket = socketRef.current - if (!socket || !token || authenticated !== true) { - return - } - - if (!socket.connected) { - logger.debug('Page visible with disconnected socket, reconnecting...') - attemptReconnect() - return - } - - if (subscribedActivityCallbacksRef.current.size > 0) { + if (socket && subscribedActivityCallbacksRef.current.size > 0) { logger.debug('Page visible, resubscribing activity listeners...') subscribedActivityServerSubscriptionsRef.current.clear() resubscribeActivityListeners(socket) } } + const handleWindowFocus = () => { + reconnectIfDisconnected('Window focused') + } + const handlePageShow = (event) => { if (!event.persisted) { return @@ -639,10 +653,12 @@ const ApiServerProvider = ({ children }) => { } document.addEventListener('visibilitychange', handlePageVisible) + window.addEventListener('focus', handleWindowFocus) window.addEventListener('pageshow', handlePageShow) return () => { document.removeEventListener('visibilitychange', handlePageVisible) + window.removeEventListener('focus', handleWindowFocus) window.removeEventListener('pageshow', handlePageShow) } }, [