From d7fb069b855d9a8c8a33600e0391507e210522e2 Mon Sep 17 00:00:00 2001 From: Chris Heo Date: Tue, 7 Jan 2025 20:35:45 -0800 Subject: [PATCH] [CLNP-6072] useConnectionHandler (#1291) https://sendbird.atlassian.net/browse/SBISSUE-18182 ### Checklist Put an `x` in the boxes that apply. You can also fill these out after creating the PR. If unsure, ask the members. This is a reminder of what we look for before merging your code. - [x] **All tests pass locally with my changes** - [ ] **I have added tests that prove my fix is effective or that my feature works** - [ ] **Public components / utils / props are appropriately exported** - [ ] I have added necessary documentation (if appropriate) ## External Contributions This project is not yet set up to accept pull requests from external contributors. If you have a pull request that you believe should be accepted, please contact the Developer Relations team with details and we'll evaluate if we can set up a [CLA](https://en.wikipedia.org/wiki/Contributor_License_Agreement) to allow for the contribution. --------- Co-authored-by: HoonBaek --- src/hooks/useConnectionState.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/hooks/useConnectionState.ts 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; +};