Skip to content

Commit

Permalink
feat: improve WebSocket reconnection in useWebsocket hook
Browse files Browse the repository at this point in the history
  • Loading branch information
keiko233 committed Mar 13, 2024
1 parent 4a2f052 commit 8039a56
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions src/hooks/use-websocket.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useRef } from "react";
import { useRef, useEffect } from "react";

export type WsMsgFn = (event: MessageEvent<any>) => void;

Expand All @@ -10,7 +10,7 @@ export interface WsOptions {

export const useWebsocket = (onMessage: WsMsgFn, options?: WsOptions) => {
const wsRef = useRef<WebSocket | null>(null);
const timerRef = useRef<any>(null);
const timerRef = useRef<number | null>(null);

const disconnect = () => {
if (wsRef.current) {
Expand All @@ -24,6 +24,7 @@ export const useWebsocket = (onMessage: WsMsgFn, options?: WsOptions) => {

const connect = (url: string) => {
let errorCount = options?.errorCount ?? 5;
const retryInterval = options?.retryInterval ?? 2500;

if (!url) return;

Expand All @@ -38,16 +39,28 @@ export const useWebsocket = (onMessage: WsMsgFn, options?: WsOptions) => {
errorCount -= 1;

if (errorCount >= 0) {
timerRef.current = setTimeout(connectHelper, 2500);
timerRef.current = window.setTimeout(connectHelper, retryInterval);
} else {
disconnect();
options?.onError?.();
}
});

ws.addEventListener("close", () => {
// WebSocket connection closed, attempt to reconnect
timerRef.current = window.setTimeout(connectHelper, retryInterval);
});
};

connectHelper();
};

useEffect(() => {
// Cleanup on component unmount
return () => {
disconnect();
};
}, []);

return { connect, disconnect };
};

0 comments on commit 8039a56

Please sign in to comment.