1
- import { useState } from 'react' ;
1
+ import { useEffect , useState } from 'react' ;
2
2
import { ConnectionState } from '@sendbird/chat' ;
3
3
4
4
import ConnectionHandler from '../lib/handlers/ConnectionHandler' ;
@@ -11,12 +11,22 @@ export const useConnectionState = (): ConnectionState => {
11
11
const { sdk } = sdkStore ;
12
12
13
13
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
+
21
31
return connectionState ;
22
32
} ;
0 commit comments