UNPKG

@react-hookz/web

Version:

React hooks done right, for browser and SSR.

50 lines (49 loc) 2.37 kB
import { useEffect } from 'react'; import { isBrowser } from "../util/const.js"; import { useSafeState } from '..'; import { off, on } from "../util/misc.js"; var navigator = isBrowser ? window.navigator : undefined; var conn = navigator && (navigator.connection || navigator.mozConnection || navigator.webkitConnection); function getConnectionState(previousState) { var online = navigator === null || navigator === void 0 ? void 0 : navigator.onLine; var previousOnline = previousState === null || previousState === void 0 ? void 0 : previousState.online; return { online: online, previous: previousOnline, since: online !== previousOnline ? new Date() : previousState === null || previousState === void 0 ? void 0 : previousState.since, 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 function useNetworkState(initialState) { var _a = useSafeState(initialState !== null && initialState !== void 0 ? initialState : getConnectionState), state = _a[0], setState = _a[1]; useEffect(function () { var handleStateChange = function () { setState(getConnectionState); }; on(window, 'online', handleStateChange, { passive: true }); on(window, 'offline', handleStateChange, { passive: true }); // it is quite hard to test it in jsdom environment maybe will be improved in future /* istanbul ignore next */ if (conn) { on(conn, 'change', handleStateChange, { passive: true }); } return function () { off(window, 'online', handleStateChange); off(window, 'offline', handleStateChange); /* istanbul ignore next */ if (conn) { off(conn, 'change', handleStateChange); } }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return state; }