1 | import { useEffect, useState } from 'react';
|
---|
2 | import { isNavigator, off, on } from './misc/util';
|
---|
3 | var nav = isNavigator ? navigator : undefined;
|
---|
4 | var conn = nav && (nav.connection || nav.mozConnection || nav.webkitConnection);
|
---|
5 | function getConnectionState(previousState) {
|
---|
6 | var online = nav === null || nav === void 0 ? void 0 : nav.onLine;
|
---|
7 | var previousOnline = previousState === null || previousState === void 0 ? void 0 : previousState.online;
|
---|
8 | return {
|
---|
9 | online: online,
|
---|
10 | previous: previousOnline,
|
---|
11 | since: online !== previousOnline ? new Date() : previousState === null || previousState === void 0 ? void 0 : previousState.since,
|
---|
12 | downlink: conn === null || conn === void 0 ? void 0 : conn.downlink,
|
---|
13 | downlinkMax: conn === null || conn === void 0 ? void 0 : conn.downlinkMax,
|
---|
14 | effectiveType: conn === null || conn === void 0 ? void 0 : conn.effectiveType,
|
---|
15 | rtt: conn === null || conn === void 0 ? void 0 : conn.rtt,
|
---|
16 | saveData: conn === null || conn === void 0 ? void 0 : conn.saveData,
|
---|
17 | type: conn === null || conn === void 0 ? void 0 : conn.type,
|
---|
18 | };
|
---|
19 | }
|
---|
20 | export default function useNetworkState(initialState) {
|
---|
21 | var _a = useState(initialState !== null && initialState !== void 0 ? initialState : getConnectionState), state = _a[0], setState = _a[1];
|
---|
22 | useEffect(function () {
|
---|
23 | var handleStateChange = function () {
|
---|
24 | setState(getConnectionState);
|
---|
25 | };
|
---|
26 | on(window, 'online', handleStateChange, { passive: true });
|
---|
27 | on(window, 'offline', handleStateChange, { passive: true });
|
---|
28 | if (conn) {
|
---|
29 | on(conn, 'change', handleStateChange, { passive: true });
|
---|
30 | }
|
---|
31 | return function () {
|
---|
32 | off(window, 'online', handleStateChange);
|
---|
33 | off(window, 'offline', handleStateChange);
|
---|
34 | if (conn) {
|
---|
35 | off(conn, 'change', handleStateChange);
|
---|
36 | }
|
---|
37 | };
|
---|
38 | }, []);
|
---|
39 | return state;
|
---|
40 | }
|
---|