beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
35 lines (34 loc) • 1.49 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var useGlobalEvent_1 = __importDefault(require("./useGlobalEvent"));
var warnOnce_1 = __importDefault(require("./shared/warnOnce"));
/**
* Uses the [Navigator online API](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine) to define
* whether the browser is connected or not.
*/
var useOnlineState = function () {
/**
* If the browser doesn't support the `navigator.onLine` state, the hook will always return true
* assuming the app is already online.
*/
var isSupported = typeof window !== 'undefined' && 'ononline' in window;
var _a = (0, react_1.useState)(isSupported ? navigator.onLine : true), isOnline = _a[0], setIsOnline = _a[1];
var whenOnline = (0, useGlobalEvent_1.default)('online', { capture: true });
var whenOffline = (0, useGlobalEvent_1.default)('offline', { capture: true });
if (!isSupported) {
(0, warnOnce_1.default)('The current device does not support the \'online/offline\' events, you should avoid using useOnlineState');
return isOnline;
}
whenOnline(function () {
setIsOnline(true);
});
whenOffline(function () {
setIsOnline(false);
});
return isOnline;
};
exports.default = useOnlineState;