Skip to content

Commit

Permalink
fix: Improve the useConnectionState hook (#1296)
Browse files Browse the repository at this point in the history
* added optional chaining & useEffect to the useConnectionHandler
  • Loading branch information
HoonBaek authored Jan 9, 2025
1 parent d7fb069 commit 17a93fe
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions src/hooks/useConnectionState.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { ConnectionState } from '@sendbird/chat';

import ConnectionHandler from '../lib/handlers/ConnectionHandler';
Expand All @@ -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;
};

0 comments on commit 17a93fe

Please sign in to comment.