rooks
Version:
Essential React custom hooks ⚓ to super charge your components!
49 lines (48 loc) • 1.36 kB
JavaScript
import { useState, useEffect } from "react";
import { noop } from "../utils/noop";
/**
*
* @returns {boolean} Is navigator online
*/
function getIsOnline() {
if (typeof window === "undefined") {
return null;
}
return navigator.onLine;
}
/**
* useOnline hook
*
* Returns true if navigator is online, false if not.
*
* @returns {boolean} The value of navigator.onLine
* @see https://react-hooks.org/docs/useOnline
*/
function useOnline() {
var _a = useState(function () { return getIsOnline(); }), isOnline = _a[0], setIsOnline = _a[1];
function setOffline() {
setIsOnline(false);
}
function setOnline() {
setIsOnline(true);
}
// we only needs this to be set on mount
// hence []
useEffect(function () {
// eslint-disable-next-line no-negated-condition
if (typeof window !== "undefined") {
window.addEventListener("online", setOnline);
window.addEventListener("offline", setOffline);
return function () {
window.removeEventListener("online", setOnline);
window.removeEventListener("offline", setOffline);
};
}
else {
console.warn("useOnline: window is undefined.");
return noop;
}
}, []);
return isOnline;
}
export { useOnline };