on df0c310 help sign in
bridge/src/store/online.jsx
66 lines 1.5 kB history raw
1import React, {
2 createContext,
3 forwardRef,
4 useContext,
5 useEffect,
6 useState,
7} from 'react';
9export const ONLINE_STATUS = {
10 ONLINE: Symbol('ONLINE'),
11 OFFLINE: Symbol('OFFLINE'),
12 UNKNOWN: Symbol('UNKNOWN'),
13};
15const getNetworkState = () => {
16 if ('onLine' in navigator) {
17 return navigator.onLine ? ONLINE_STATUS.ONLINE : ONLINE_STATUS.OFFLINE;
18 }
20 return ONLINE_STATUS.UNKNOWN;
21};
23function _useOnline() {
24 const [online, setOnline] = useState(getNetworkState());
26 useEffect(() => {
27 function handleOnlineStatus(event) {
28 setOnline(getNetworkState());
29 }
31 window.addEventListener('online', handleOnlineStatus);
32 window.addEventListener('offline', handleOnlineStatus);
34 return () => {
35 window.removeEventListener('online', handleOnlineStatus);
36 window.removeEventListener('offline', handleOnlineStatus);
37 };
38 }, []);
40 return online;
43const OnlineContext = createContext(null);
45// provider
46export function OnlineProvider({ children }) {
47 const online = _useOnline();
48 return (
49 <OnlineContext.Provider value={online}>{children}</OnlineContext.Provider>
50 );
53// hook consumer
54export function useOnline() {
55 return useContext(OnlineContext);
58// hoc consumer
59export const withOnline = Component =>
60 forwardRef((props, ref) => {
61 return (
62 <OnlineContext.Consumer>
63 {online => <Component ref={ref} online={online} {...props} />}
64 </OnlineContext.Consumer>
65 );
66 });