1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | import {useState, useEffect} from 'react';
|
11 | import DEFAULT_CONFIGURATION from './internal/defaultConfiguration';
|
12 | import State from './internal/state';
|
13 | import * as Types from './internal/types';
|
14 |
|
15 |
|
16 | let _configuration: Types.NetInfoConfiguration = DEFAULT_CONFIGURATION;
|
17 |
|
18 |
|
19 | let _state: State | null = null;
|
20 | const createState = (): State => {
|
21 | return new State(_configuration);
|
22 | };
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | export function configure(
|
32 | configuration: Partial<Types.NetInfoConfiguration>,
|
33 | ): void {
|
34 | _configuration = {
|
35 | ...DEFAULT_CONFIGURATION,
|
36 | ...configuration,
|
37 | };
|
38 |
|
39 | if (_state) {
|
40 | _state.tearDown();
|
41 | _state = createState();
|
42 | }
|
43 | }
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 | export function fetch(
|
53 | requestedInterface?: string,
|
54 | ): Promise<Types.NetInfoState> {
|
55 | if (!_state) {
|
56 | _state = createState();
|
57 | }
|
58 | return _state.latest(requestedInterface);
|
59 | }
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 | export function addEventListener(
|
73 | listener: Types.NetInfoChangeHandler,
|
74 | ): Types.NetInfoSubscription {
|
75 | if (!_state) {
|
76 | _state = createState();
|
77 | }
|
78 |
|
79 | _state.add(listener);
|
80 | return (): void => {
|
81 | _state && _state.remove(listener);
|
82 | };
|
83 | }
|
84 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 | export function useNetInfo(
|
91 | configuration?: Partial<Types.NetInfoConfiguration>,
|
92 | ): Types.NetInfoState {
|
93 | if (configuration) {
|
94 | configure(configuration);
|
95 | }
|
96 |
|
97 | const [netInfo, setNetInfo] = useState<Types.NetInfoState>({
|
98 | type: Types.NetInfoStateType.unknown,
|
99 | isConnected: null,
|
100 | isInternetReachable: null,
|
101 | details: null,
|
102 | });
|
103 |
|
104 | useEffect((): (() => void) => {
|
105 | return addEventListener(setNetInfo);
|
106 | }, []);
|
107 |
|
108 | return netInfo;
|
109 | }
|
110 |
|
111 | export * from './internal/types';
|
112 |
|
113 | export default {
|
114 | configure,
|
115 | fetch,
|
116 | addEventListener,
|
117 | useNetInfo,
|
118 | };
|