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.
This commit is contained in:
parent
b925518e69
commit
4ca7ecbb6a
@ -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)
|
||||
}
|
||||
}, [
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user