UNPKG

@react-hookz/web

Version:

React hooks done right, for browser and SSR.

54 lines (53 loc) 2.59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useNetworkState = void 0; var react_1 = require("react"); var const_1 = require("../util/const"); var __1 = require(".."); var misc_1 = require("../util/misc"); var navigator = const_1.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. */ function useNetworkState(initialState) { var _a = (0, __1.useSafeState)(initialState !== null && initialState !== void 0 ? initialState : getConnectionState), state = _a[0], setState = _a[1]; (0, react_1.useEffect)(function () { var handleStateChange = function () { setState(getConnectionState); }; (0, misc_1.on)(window, 'online', handleStateChange, { passive: true }); (0, misc_1.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) { (0, misc_1.on)(conn, 'change', handleStateChange, { passive: true }); } return function () { (0, misc_1.off)(window, 'online', handleStateChange); (0, misc_1.off)(window, 'offline', handleStateChange); /* istanbul ignore next */ if (conn) { (0, misc_1.off)(conn, 'change', handleStateChange); } }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return state; } exports.useNetworkState = useNetworkState;