-
Notifications
You must be signed in to change notification settings - Fork 9
/
useNetworkQuality.ts
48 lines (43 loc) · 1.43 KB
/
useNetworkQuality.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
import type { IAgoraRTCClient } from "agora-rtc-sdk-ng";
import { useEffect, useState } from "react";
import { useRTCClient } from "../hooks/useRTCClient";
import { listen } from "../misc/listen";
import type { NetworkQualityEx } from "../types";
const initQuality = (): NetworkQualityEx => ({
uplinkNetworkQuality: 0,
downlinkNetworkQuality: 0,
delay: 0,
});
/**
* Returns the network quality of the local user.
*
* @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 { useNetworkQuality } from "agora-rtc-react";
*
* function App() {
* const networkQuality = useNetworkQuality();
*
* return <div>{networkQuality}</div>;
* }
* ```
*/
export function useNetworkQuality(client?: IAgoraRTCClient | null): NetworkQualityEx {
const resolvedClient = useRTCClient(client);
const [networkQuality, setNetworkQuality] = useState<NetworkQualityEx>(initQuality);
useEffect(() => {
if (resolvedClient) {
return listen(resolvedClient, "network-quality", q =>
setNetworkQuality({
uplinkNetworkQuality: q.uplinkNetworkQuality,
downlinkNetworkQuality: q.downlinkNetworkQuality,
delay: resolvedClient.getRTCStats().RTT ?? 0,
}),
);
} else {
setNetworkQuality(initQuality());
}
}, [resolvedClient]);
return networkQuality;
}