From 17a93fe93c25cc41b3543d54f1f7356057a5143b Mon Sep 17 00:00:00 2001 From: Baek EunSeo Date: Thu, 9 Jan 2025 15:51:12 +0900 Subject: [PATCH] fix: Improve the useConnectionState hook (#1296) * added optional chaining & useEffect to the useConnectionHandler --- src/hooks/useConnectionState.ts | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/hooks/useConnectionState.ts b/src/hooks/useConnectionState.ts index d5f43bf23..403dbba82 100644 --- a/src/hooks/useConnectionState.ts +++ b/src/hooks/useConnectionState.ts @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useEffect, useState } from 'react'; import { ConnectionState } from '@sendbird/chat'; import ConnectionHandler from '../lib/handlers/ConnectionHandler'; @@ -11,12 +11,22 @@ export const useConnectionState = (): ConnectionState => { const { sdk } = sdkStore; const [connectionState, setConnectionState] = useState(sdk.connectionState); - sdk.addConnectionHandler(uuidv4(), new ConnectionHandler({ - onConnected: () => setConnectionState(ConnectionState.OPEN), - onDisconnected: () => setConnectionState(ConnectionState.CLOSED), - onReconnectStarted: () => setConnectionState(ConnectionState.CONNECTING), - onReconnectSucceeded: () => setConnectionState(ConnectionState.OPEN), - onReconnectFailed: () => setConnectionState(ConnectionState.CLOSED), - })); + + useEffect(() => { + const handlerId = uuidv4(); + + sdk?.addConnectionHandler(handlerId, new ConnectionHandler({ + onConnected: () => setConnectionState(ConnectionState.OPEN), + onDisconnected: () => setConnectionState(ConnectionState.CLOSED), + onReconnectStarted: () => setConnectionState(ConnectionState.CONNECTING), + onReconnectSucceeded: () => setConnectionState(ConnectionState.OPEN), + onReconnectFailed: () => setConnectionState(ConnectionState.CLOSED), + })); + + return () => { + sdk?.removeConnectionHandler(handlerId); + }; + }, [sdk]); + return connectionState; };