Exponential backoff with useRef

This commit is contained in:
projectmoon 2024-08-01 17:12:21 +02:00
parent f2fbc5db25
commit df8d924a89
1 changed files with 14 additions and 2 deletions

View File

@ -47,6 +47,8 @@ const useSocket = (
hasError: boolean hasError: boolean
) => { ) => {
const [ws, setWs] = useState<WebSocket | null>(null); const [ws, setWs] = useState<WebSocket | null>(null);
const reconnectTimeout = useRef(0);
const reconnectAttempts = useRef(0);
useEffect(() => { useEffect(() => {
if (!ws) { if (!ws) {
@ -203,6 +205,8 @@ const useSocket = (
ws.onopen = () => { ws.onopen = () => {
console.log('[DEBUG] open'); console.log('[DEBUG] open');
reconnectTimeout.current = 0;
reconnectAttempts.current = 0;
clearTimeout(timeoutId); clearTimeout(timeoutId);
setError(false); setError(false);
setIsWSReady(true); setIsWSReady(true);
@ -216,7 +220,7 @@ const useSocket = (
ws.onclose = () => { ws.onclose = () => {
clearTimeout(timeoutId); clearTimeout(timeoutId);
if (!hasError) { if (!hasError && reconnectAttempts.current < 3) {
setWs(null); // forces websocket to reopen when needed. setWs(null); // forces websocket to reopen when needed.
} }
console.log('[DEBUG] closed'); console.log('[DEBUG] closed');
@ -232,7 +236,15 @@ const useSocket = (
setWs(ws); setWs(ws);
}; };
connectWs(); if (reconnectAttempts.current < 3) {
console.log(`[DEBUG] Attempting to reconnect (${reconnectAttempts.current + 1}/3)`);
setTimeout(connectWs, reconnectTimeout.current);
reconnectTimeout.current = reconnectTimeout.current > 0 ? reconnectTimeout.current * 2 : 1000;
reconnectAttempts.current += 1;
} else {
console.log('[DEBUG] WebSocket reconnect failure after 3 retries');
setError(true);
}
} }
return () => { return () => {