Skip to content

Commit

Permalink
refactor: add server page reconnect
Browse files Browse the repository at this point in the history
  • Loading branch information
moonrailgun committed Apr 27, 2024
1 parent dd8ea66 commit c950e4a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/client/api/socketio.ts
Expand Up @@ -86,7 +86,7 @@ export function useSocket() {
}
);

return { emit, subscribe };
return { socket, emit, subscribe };
}

export function useSocketSubscribe<T>(
Expand Down
13 changes: 12 additions & 1 deletion 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<string, ServerStatusInfo> {
const { socket } = useSocket();
const serverMap = useSocketSubscribe<Record<string, ServerStatusInfo>>(
'onServerStatusUpdate',
{}
);

/**
* Auto reconnect when reconnect
*/
useVisibilityChange((visibility) => {
if (visibility && socket?.disconnected === true) {
socket.connect();
}
});

return serverMap;
}
22 changes: 22 additions & 0 deletions 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);
};
}, []);
}

0 comments on commit c950e4a

Please sign in to comment.