UNPKG

@supunlakmal/hooks

Version:

A collection of reusable React hooks

49 lines 2.25 kB
var _a, _b; import { useEffect, useState } from 'react'; import { isBrowser } from '../../util/const'; import { off, on } from '../../util/misc'; const navigator = isBrowser ? globalThis.navigator : undefined; const conn = navigator && ((_b = (_a = navigator.connection) !== null && _a !== void 0 ? _a : navigator.mozConnection) !== null && _b !== void 0 ? _b : navigator.webkitConnection); const getConnectionState = (previousState) => { const online = navigator === null || navigator === void 0 ? void 0 : navigator.onLine; const previousOnline = previousState === null || previousState === void 0 ? void 0 : previousState.online; return { online, previous: previousOnline, since: online === previousOnline ? previousState === null || previousState === void 0 ? void 0 : previousState.since : new Date(), downlink: conn === null || conn === void 0 ? void 0 : conn.downlink, downlinkMax: conn === null || conn === void 0 ? void 0 : conn.downlinkMax, effectiveType: conn === null || conn === void 0 ? void 0 : conn.effectiveType, rtt: conn === null || conn === void 0 ? void 0 : conn.rtt, saveData: conn === null || conn === void 0 ? void 0 : conn.saveData, type: conn === null || conn === void 0 ? void 0 : conn.type, }; }; /** * Tracks the state of browser's network connection. */ export const useNetworkState = (initialState) => { const [state, setState] = useState(initialState !== null && initialState !== void 0 ? initialState : getConnectionState); useEffect(() => { const handleStateChange = () => { setState(getConnectionState); }; on(globalThis, 'online', handleStateChange, { passive: true }); on(globalThis, 'offline', handleStateChange, { passive: true }); if (conn) { on(conn, 'change', handleStateChange, { passive: true }); } return () => { off(globalThis, 'online', handleStateChange); off(globalThis, 'offline', handleStateChange); if (conn) { off(conn, 'change', handleStateChange); } }; }, []); return state; }; //# sourceMappingURL=useNetworkState.js.map