refactor: add server page reconnect
This commit is contained in:
parent
dd8ea6623f
commit
c950e4a3f8
@ -86,7 +86,7 @@ export function useSocket() {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
return { emit, subscribe };
|
return { socket, emit, subscribe };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useSocketSubscribe<T>(
|
export function useSocketSubscribe<T>(
|
||||||
|
@ -1,11 +1,22 @@
|
|||||||
import { useSocketSubscribe } from '@/api/socketio';
|
import { useSocket, useSocketSubscribe } from '@/api/socketio';
|
||||||
import { ServerStatusInfo } from '../../../types';
|
import { ServerStatusInfo } from '../../../types';
|
||||||
|
import { useVisibilityChange } from '@/hooks/useVisibilityChange';
|
||||||
|
|
||||||
export function useServerMap(): Record<string, ServerStatusInfo> {
|
export function useServerMap(): Record<string, ServerStatusInfo> {
|
||||||
|
const { socket } = useSocket();
|
||||||
const serverMap = useSocketSubscribe<Record<string, ServerStatusInfo>>(
|
const serverMap = useSocketSubscribe<Record<string, ServerStatusInfo>>(
|
||||||
'onServerStatusUpdate',
|
'onServerStatusUpdate',
|
||||||
{}
|
{}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Auto reconnect when reconnect
|
||||||
|
*/
|
||||||
|
useVisibilityChange((visibility) => {
|
||||||
|
if (visibility && socket?.disconnected === true) {
|
||||||
|
socket.connect();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
return serverMap;
|
return serverMap;
|
||||||
}
|
}
|
||||||
|
22
src/client/hooks/useVisibilityChange.ts
Normal file
22
src/client/hooks/useVisibilityChange.ts
Normal 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);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user