react-query
Version:
Hooks for managing, caching and syncing asynchronous and remote data in React
107 lines (80 loc) • 2.72 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.onlineManager = exports.OnlineManager = void 0;
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _subscribable = require("./subscribable");
var _utils = require("./utils");
var OnlineManager = /*#__PURE__*/function (_Subscribable) {
(0, _inheritsLoose2.default)(OnlineManager, _Subscribable);
function OnlineManager() {
var _this;
_this = _Subscribable.call(this) || this;
_this.setup = function (onOnline) {
var _window;
if (!_utils.isServer && ((_window = window) == null ? void 0 : _window.addEventListener)) {
var listener = function listener() {
return onOnline();
}; // Listen to online
window.addEventListener('online', listener, false);
window.addEventListener('offline', listener, false);
return function () {
// Be sure to unsubscribe if a new handler is set
window.removeEventListener('online', listener);
window.removeEventListener('offline', listener);
};
}
};
return _this;
}
var _proto = OnlineManager.prototype;
_proto.onSubscribe = function onSubscribe() {
if (!this.cleanup) {
this.setEventListener(this.setup);
}
};
_proto.onUnsubscribe = function onUnsubscribe() {
if (!this.hasListeners()) {
var _this$cleanup;
(_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
this.cleanup = undefined;
}
};
_proto.setEventListener = function setEventListener(setup) {
var _this$cleanup2,
_this2 = this;
this.setup = setup;
(_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
this.cleanup = setup(function (online) {
if (typeof online === 'boolean') {
_this2.setOnline(online);
} else {
_this2.onOnline();
}
});
};
_proto.setOnline = function setOnline(online) {
this.online = online;
if (online) {
this.onOnline();
}
};
_proto.onOnline = function onOnline() {
this.listeners.forEach(function (listener) {
listener();
});
};
_proto.isOnline = function isOnline() {
if (typeof this.online === 'boolean') {
return this.online;
}
if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
return true;
}
return navigator.onLine;
};
return OnlineManager;
}(_subscribable.Subscribable);
exports.OnlineManager = OnlineManager;
var onlineManager = new OnlineManager();
exports.onlineManager = onlineManager;