Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useWebSocket): add on max attempt callback #2538

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions packages/hooks/src/useWebSocket/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,52 @@ describe('useWebSocket', () => {
act(() => wsServer2.close());
});
});

it('should call onMaxAttempt when reconnect attempts exceeded and unable to connect to server', async () => {
const onMaxAttempt = jest.fn();

renderHook(() =>
useWebSocket('ws://localhost:8888', {
onMaxAttempt,
reconnectInterval: 100,
}),
);

await act(async () => {
await sleep(500);
});

expect(onMaxAttempt).toBeCalledTimes(1);
});

it('should call onMaxAttempt when reconnect attempts exceed and server disconnects', async () => {
const onMaxAttempt = jest.fn();

const wsServer = new WS(wsUrl);

renderHook(() =>
useWebSocket(wsUrl, {
onMaxAttempt,
reconnectInterval: 100,
reconnectLimit: 1,
}),
);

await act(async () => {
await wsServer.connected;
});

wsServer.close();

await act(async () => {
await wsServer.connected;
});

wsServer.close();

await act(async () => {
await sleep(500);
});

expect(onMaxAttempt).toBeCalledTimes(1);
});
1 change: 1 addition & 0 deletions packages/hooks/src/useWebSocket/index.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ useWebSocket(socketUrl: string, options?: Options): Result;
| onClose | WebSocket close callback | `(event: WebSocketEventMap['close'], instance: WebSocket) => void` | - |
| onMessage | WebSocket receive message callback | `(message: WebSocketEventMap['message'], instance: WebSocket) => void` | - |
| onError | WebSocket error callback | `(event: WebSocketEventMap['error'], instance: WebSocket) => void` | - |
| onMaxAttempt | Reconnect attempts exceed callback | `() => void` | - |
| reconnectLimit | Retry times | `number` | `3` |
| reconnectInterval | Retry interval(ms) | `number` | `3000` |
| manual | Manually starts connection | `boolean` | `false` |
Expand Down
16 changes: 16 additions & 0 deletions packages/hooks/src/useWebSocket/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export interface Options {
onClose?: (event: WebSocketEventMap['close'], instance: WebSocket) => void;
onMessage?: (message: WebSocketEventMap['message'], instance: WebSocket) => void;
onError?: (event: WebSocketEventMap['error'], instance: WebSocket) => void;
onMaxAttempt?: () => void;

protocols?: string | string[];
}
Expand All @@ -40,17 +41,20 @@ export default function useWebSocket(socketUrl: string, options: Options = {}):
onClose,
onMessage,
onError,
onMaxAttempt,
protocols,
} = options;

const onOpenRef = useLatest(onOpen);
const onCloseRef = useLatest(onClose);
const onMessageRef = useLatest(onMessage);
const onErrorRef = useLatest(onError);
const onMaxAttemptRef = useLatest(onMaxAttempt);

const reconnectTimesRef = useRef(0);
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout>>();
const websocketRef = useRef<WebSocket>();
const maxAttemptThrottle = useRef<ReturnType<typeof setTimeout>>();

const [latestMessage, setLatestMessage] = useState<WebSocketEventMap['message']>();
const [readyState, setReadyState] = useState<ReadyState>(ReadyState.Closed);
Expand All @@ -69,6 +73,14 @@ export default function useWebSocket(socketUrl: string, options: Options = {}):
connectWs();
reconnectTimesRef.current++;
}, reconnectInterval);
} else {
if (maxAttemptThrottle.current) {
clearTimeout(maxAttemptThrottle.current);
}

maxAttemptThrottle.current = setTimeout(() => {
onMaxAttemptRef.current?.();
}, 100);
}
};

Expand Down Expand Up @@ -140,6 +152,10 @@ export default function useWebSocket(socketUrl: string, options: Options = {}):
clearTimeout(reconnectTimerRef.current);
}

if (maxAttemptThrottle.current) {
clearTimeout(maxAttemptThrottle.current);
}

reconnectTimesRef.current = reconnectLimit;
websocketRef.current?.close();
websocketRef.current = undefined;
Expand Down
1 change: 1 addition & 0 deletions packages/hooks/src/useWebSocket/index.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ useWebSocket(socketUrl: string, options?: Options): Result;
| onClose | webSocket 关闭回调 | `(event: WebSocketEventMap['close'], instance: WebSocket) => void` | - |
| onMessage | webSocket 收到消息回调 | `(message: WebSocketEventMap['message'], instance: WebSocket) => void` | - |
| onError | webSocket 错误回调 | `(event: WebSocketEventMap['error'], instance: WebSocket) => void` | - |
| onMaxAttempt | 重试最大次数回调 | `() => void` | - |
| reconnectLimit | 重试次数 | `number` | `3` |
| reconnectInterval | 重试时间间隔(ms) | `number` | `3000` |
| manual | 手动启动连接 | `boolean` | `false` |
Expand Down
Loading