1- import { useState } from 'react' ;
1+ import { useEffect , useState } from 'react' ;
22import { ConnectionState } from '@sendbird/chat' ;
33
44import 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