-
Notifications
You must be signed in to change notification settings - Fork 9
/
useConnectionState.ts
51 lines (47 loc) · 1.61 KB
/
useConnectionState.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import type { ConnectionState, IAgoraRTCClient } from "agora-rtc-sdk-ng";
import { useEffect, useState } from "react";
import { useRTCClient } from "../hooks/useRTCClient";
import { listen } from "../misc/listen";
import { joinDisposers, timeout } from "../misc/utils";
/**
* Returns the detailed connection state of the SDK.
*
* @param client - Created using the Web SDK's [`IAgoraRTC.createClient`](https://api-ref.agora.io/en/video-sdk/web/4.x/interfaces/iagorartc.html#createclient) method.
* @example
* ```jsx
* import { useConnectionState } from "agora-rtc-react";
*
* function App() {
* const connectionState = useConnectionState();
*
* return <div>{connectionState}</div>;
* }
* ```
*/
export function useConnectionState(client?: IAgoraRTCClient | null): ConnectionState {
const resolvedClient = useRTCClient(client);
const [connectionState, setConnectionState] = useState(
resolvedClient ? resolvedClient.connectionState : "DISCONNECTED",
);
useEffect(() => {
if (resolvedClient) {
setConnectionState(resolvedClient.connectionState);
let dispose: (() => void) | undefined;
return joinDisposers([
listen(resolvedClient, "connection-state-change", state => {
dispose?.();
if (state === "CONNECTED") {
// RTC is really connected after a short delay
dispose = timeout(() => setConnectionState(state), 0);
} else {
setConnectionState(state);
}
}),
() => dispose?.(),
]);
} else {
setConnectionState("DISCONNECTED");
}
}, [resolvedClient]);
return connectionState;
}