diff --git a/src/hooks/useConnectionState.ts b/src/hooks/useConnectionState.ts new file mode 100644 index 000000000..d5f43bf23 --- /dev/null +++ b/src/hooks/useConnectionState.ts @@ -0,0 +1,22 @@ +import { useState } from 'react'; +import { ConnectionState } from '@sendbird/chat'; + +import ConnectionHandler from '../lib/handlers/ConnectionHandler'; +import useSendbirdStateContext from './useSendbirdStateContext'; +import uuidv4 from '../utils/uuid'; + +export const useConnectionState = (): ConnectionState => { + const { stores } = useSendbirdStateContext(); + const { sdkStore } = stores; + 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), + })); + return connectionState; +};