UNPKG

@hooks/network-status

Version:

React hook return network status details

28 lines (27 loc) 1.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = require("react"); const ONLINE = 'online'; const OFFLINE = 'offline'; function useNetworkStatus() { var _a; const [status, setStatus] = react_1.useState({ online: typeof window !== 'undefined' ? (_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.onLine : undefined, }); react_1.useEffect(() => { const updateOnlineStatus = () => { setStatus(prevStatus => { var _a; return (Object.assign(Object.assign({}, prevStatus), { online: typeof window !== 'undefined' ? (_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.onLine : undefined })); }); }; window.addEventListener(ONLINE, updateOnlineStatus); window.addEventListener(OFFLINE, updateOnlineStatus); return () => { window.removeEventListener(ONLINE, updateOnlineStatus); window.removeEventListener(OFFLINE, updateOnlineStatus); }; }, []); return status; } exports.default = useNetworkStatus;