@storm-stack/hooks
Version:
A collection of React hooks used by Storm Software in various client libraries and applications.
63 lines (62 loc) • 1.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useNetworkState = useNetworkState;
exports.useNetworkStateSubscribe = void 0;
var _isEqual = require("@storm-stack/types/type-checks/is-equal");
var _react = require("react");
const getConnection = () => {
const connectionKey = "connection";
const mozConnectionKey = "mozConnection";
const webkitConnectionKey = "webkitConnection";
return navigator[connectionKey] || navigator[mozConnectionKey] || navigator[webkitConnectionKey];
};
const useNetworkStateSubscribe = callback => {
window.addEventListener("online", callback, {
passive: true
});
window.addEventListener("offline", callback, {
passive: true
});
const connection = getConnection();
if (connection) {
connection.addEventListener("change", callback, {
passive: true
});
}
return () => {
window.removeEventListener("online", callback);
window.removeEventListener("offline", callback);
if (connection) {
connection.removeEventListener("change", callback);
}
};
};
exports.useNetworkStateSubscribe = useNetworkStateSubscribe;
const getNetworkStateServerSnapshot = () => {
throw Error("useNetworkState is a client-only hook");
};
function useNetworkState() {
const cache = (0, _react.useRef)({});
const getSnapshot = () => {
const online = navigator.onLine;
const connection = getConnection();
const nextState = {
online,
downlink: connection?.downlink,
downlinkMax: connection?.downlinkMax,
effectiveType: connection?.effectiveType,
rtt: connection?.rtt,
saveData: connection?.saveData,
type: connection?.type
};
if ((0, _isEqual.isEqual)(cache.current, nextState)) {
return cache.current;
} else {
cache.current = nextState;
return nextState;
}
};
return (0, _react.useSyncExternalStore)(useNetworkStateSubscribe, getSnapshot, getNetworkStateServerSnapshot);
}