diff --git a/src/client/api/socketio.ts b/src/client/api/socketio.ts index e89391b..80b1ebe 100644 --- a/src/client/api/socketio.ts +++ b/src/client/api/socketio.ts @@ -86,7 +86,7 @@ export function useSocket() { } ); - return { emit, subscribe }; + return { socket, emit, subscribe }; } export function useSocketSubscribe( diff --git a/src/client/components/server/useServerMap.ts b/src/client/components/server/useServerMap.ts index 863345a..9442a2b 100644 --- a/src/client/components/server/useServerMap.ts +++ b/src/client/components/server/useServerMap.ts @@ -1,11 +1,22 @@ -import { useSocketSubscribe } from '@/api/socketio'; +import { useSocket, useSocketSubscribe } from '@/api/socketio'; import { ServerStatusInfo } from '../../../types'; +import { useVisibilityChange } from '@/hooks/useVisibilityChange'; export function useServerMap(): Record { + const { socket } = useSocket(); const serverMap = useSocketSubscribe>( 'onServerStatusUpdate', {} ); + /** + * Auto reconnect when reconnect + */ + useVisibilityChange((visibility) => { + if (visibility && socket?.disconnected === true) { + socket.connect(); + } + }); + return serverMap; } diff --git a/src/client/hooks/useVisibilityChange.ts b/src/client/hooks/useVisibilityChange.ts new file mode 100644 index 0000000..afd4847 --- /dev/null +++ b/src/client/hooks/useVisibilityChange.ts @@ -0,0 +1,22 @@ +import { useEffect } from 'react'; +import { useEvent } from './useEvent'; + +export function useVisibilityChange(callback: (visibility: boolean) => void) { + const fn = useEvent(callback); + + useEffect(() => { + const handleVisibilityChange = () => { + if (document.visibilityState === 'visible') { + fn(true); + } else { + fn(false); + } + }; + + document.addEventListener('visibilitychange', handleVisibilityChange); + + return () => { + document.removeEventListener('visibilitychange', handleVisibilityChange); + }; + }, []); +}