fix(panel): keep WebSocket alive across route transitions
Some checks failed
Deploy to Production / test (push) Failing after 33s
Some checks failed
Deploy to Production / test (push) Failing after 33s
Disconnecting and reconnecting the WebSocket on every route change caused a race condition: the old socket's async onclose handler would null out globalWs after the new socket was created, causing JOIN_ROOM messages to be silently dropped. The WebSocket is a global singleton — keep it alive and let the built-in reconnection logic handle actual disconnects. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useRef, useCallback, useState } from "react";
|
import { useEffect, useCallback, useState } from "react";
|
||||||
|
|
||||||
type MessageHandler = (data: any) => void;
|
type MessageHandler = (data: any) => void;
|
||||||
|
|
||||||
@@ -50,23 +50,11 @@ function connect(): void {
|
|||||||
globalWs = ws;
|
globalWs = ws;
|
||||||
}
|
}
|
||||||
|
|
||||||
function disconnect(): void {
|
|
||||||
if (reconnectTimer) {
|
|
||||||
clearTimeout(reconnectTimer);
|
|
||||||
reconnectTimer = null;
|
|
||||||
}
|
|
||||||
globalWs?.close();
|
|
||||||
globalWs = null;
|
|
||||||
globalConnected = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useWebSocket() {
|
export function useWebSocket() {
|
||||||
const [connected, setConnected] = useState(globalConnected);
|
const [connected, setConnected] = useState(globalConnected);
|
||||||
const refCount = useRef(0);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
refCount.current++;
|
if (!globalWs) {
|
||||||
if (refCount.current === 1 && !globalWs) {
|
|
||||||
connect();
|
connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,10 +66,6 @@ export function useWebSocket() {
|
|||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
globalHandlers.delete(handler);
|
globalHandlers.delete(handler);
|
||||||
refCount.current--;
|
|
||||||
if (refCount.current === 0) {
|
|
||||||
disconnect();
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user