use-navigator-online
Version:
React Hooks to detect when your browser is online/offline.
43 lines (37 loc) • 1.51 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
typeof define === 'function' && define.amd ? define(['react'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.useNavigatorOnline = factory(global.React));
})(this, (function (react) { 'use strict';
function useNavigatorOnline() {
const supported = typeof window !== "undefined" && typeof navigator !== "undefined" && "onLine" in navigator;
const [isOnline, setIsOnline] = react.useState({
previous: supported ? navigator.onLine : false,
current: supported ? navigator.onLine : false
});
react.useEffect(() => {
if (supported) {
const updateStatus = event => {
setIsOnline({
previous: isOnline.current,
current: event.type === "online"
});
};
window.addEventListener("offline", updateStatus);
window.addEventListener("online", updateStatus);
return () => {
window.removeEventListener("offline", updateStatus);
window.removeEventListener("online", updateStatus);
};
}
return () => {};
}, [isOnline, supported]);
return {
backOnline: !isOnline.previous && isOnline.current,
backOffline: isOnline.previous && !isOnline.current,
isOnline: isOnline.current,
isOffline: !isOnline.current
};
}
return useNavigatorOnline;
}));