refactor: add server page reconnect

This commit is contained in:
moonrailgun 2024-04-27 20:20:31 +08:00
parent dd8ea6623f
commit c950e4a3f8
3 changed files with 35 additions and 2 deletions

View File

@ -86,7 +86,7 @@ export function useSocket() {
}
);
return { emit, subscribe };
return { socket, emit, subscribe };
}
export function useSocketSubscribe<T>(

View File

@ -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;
}

View File

@ -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);
};
}, []);
}