Skip to content

Commit 17a93fe

Browse files
authored
fix: Improve the useConnectionState hook (#1296)
* added optional chaining & useEffect to the useConnectionHandler
1 parent d7fb069 commit 17a93fe

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

src/hooks/useConnectionState.ts

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useState } from 'react';
1+
import { useEffect, useState } from 'react';
22
import { ConnectionState } from '@sendbird/chat';
33

44
import ConnectionHandler from '../lib/handlers/ConnectionHandler';
@@ -11,12 +11,22 @@ export const useConnectionState = (): ConnectionState => {
1111
const { sdk } = sdkStore;
1212

1313
const [connectionState, setConnectionState] = useState(sdk.connectionState);
14-
sdk.addConnectionHandler(uuidv4(), new ConnectionHandler({
15-
onConnected: () => setConnectionState(ConnectionState.OPEN),
16-
onDisconnected: () => setConnectionState(ConnectionState.CLOSED),
17-
onReconnectStarted: () => setConnectionState(ConnectionState.CONNECTING),
18-
onReconnectSucceeded: () => setConnectionState(ConnectionState.OPEN),
19-
onReconnectFailed: () => setConnectionState(ConnectionState.CLOSED),
20-
}));
14+
15+
useEffect(() => {
16+
const handlerId = uuidv4();
17+
18+
sdk?.addConnectionHandler(handlerId, new ConnectionHandler({
19+
onConnected: () => setConnectionState(ConnectionState.OPEN),
20+
onDisconnected: () => setConnectionState(ConnectionState.CLOSED),
21+
onReconnectStarted: () => setConnectionState(ConnectionState.CONNECTING),
22+
onReconnectSucceeded: () => setConnectionState(ConnectionState.OPEN),
23+
onReconnectFailed: () => setConnectionState(ConnectionState.CLOSED),
24+
}));
25+
26+
return () => {
27+
sdk?.removeConnectionHandler(handlerId);
28+
};
29+
}, [sdk]);
30+
2131
return connectionState;
2232
};

0 commit comments

Comments
 (0)