Skip to content

Commit 072fd8e

Browse files
author
Davi de Medeiros
committed
register socket's close event handler earlier instead of on last unsubscription
also use addEventListener instead of reassigning and losing the previous socket-like close handlers this was causing a bug where only the first subscriber of a shared socket would have its handler invoked, since its listener was only being registered when cleaning unsubscribers for the last subscription for a url
1 parent 979b406 commit 072fd8e

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

src/lib/create-or-join.ts

+14-10
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,21 @@ const cleanSubscribers = (
1717
) => {
1818
return () => {
1919
removeSubscriber(url, subscriber);
20+
21+
const socketLike = sharedWebSockets[url];
22+
23+
if (socketLike instanceof WebSocket) {
24+
socketLike.addEventListener('close', (event: WebSocketEventMap['close']) => {
25+
if (optionsRef.current.onClose) {
26+
optionsRef.current.onClose(event);
27+
}
28+
29+
subscriber.setReadyState(ReadyState.CLOSED);
30+
});
31+
}
32+
2033
if (!hasSubscribers(url)) {
2134
try {
22-
const socketLike = sharedWebSockets[url];
23-
if (socketLike instanceof WebSocket) {
24-
socketLike.onclose = (event: WebSocketEventMap['close']) => {
25-
if (optionsRef.current.onClose) {
26-
optionsRef.current.onClose(event);
27-
}
28-
setReadyState(ReadyState.CLOSED);
29-
};
30-
}
3135
socketLike.close();
3236
} catch (e) {
3337

@@ -83,7 +87,7 @@ export const createOrJoinSocket = (
8387
reconnectCount,
8488
reconnect: startRef,
8589
};
86-
90+
8791
addSubscriber(url, subscriber);
8892

8993
return cleanSubscribers(

0 commit comments

Comments
 (0)