forked from Kieran/snort
Compare commits
1 Commits
main
...
enhancemen
Author | SHA1 | Date | |
---|---|---|---|
f05cf9426f |
76
packages/app/src/Hooks/useNetwork.tsx
Normal file
76
packages/app/src/Hooks/useNetwork.tsx
Normal file
@ -0,0 +1,76 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function useNetwork() {
|
||||
function getConnection(){
|
||||
return window.navigator.connection || window.navigator.mozConnection || window.navigator.webkitConnection || null;
|
||||
}
|
||||
|
||||
function getConnectionInfo() {
|
||||
const connection = getConnection();
|
||||
|
||||
if (!connection) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
rtt: connection.rtt,
|
||||
type: connection.type,
|
||||
saveData: connection.saveData,
|
||||
downLink: connection.downLink,
|
||||
downLinkMax: connection.downLinkMax,
|
||||
effectiveType: connection.effectiveType,
|
||||
};
|
||||
}
|
||||
|
||||
const [state, setState] = useState(() => {
|
||||
return {
|
||||
online: navigator.onLine,
|
||||
...getConnectionInfo(),
|
||||
};
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
console.log('Network online')
|
||||
|
||||
const handleOnline = () => {
|
||||
setState((prevState) => ({
|
||||
...prevState,
|
||||
online: true
|
||||
}));
|
||||
};
|
||||
|
||||
const handleOffline = () => {
|
||||
console.log('Network offline')
|
||||
|
||||
setState((prevState) => ({
|
||||
...prevState,
|
||||
online: false
|
||||
}));
|
||||
};
|
||||
|
||||
const handleConnectionChange = () => {
|
||||
const connInfo = getConnectionInfo();
|
||||
console.log('Network Connection changed '+ JSON.stringify(connInfo))
|
||||
|
||||
setState((prevState) => ({
|
||||
...prevState,
|
||||
...getConnectionInfo(),
|
||||
}));
|
||||
};
|
||||
|
||||
window.addEventListener("online", handleOnline);
|
||||
window.addEventListener("offline", handleOffline);
|
||||
|
||||
const networkConnection = getConnection();
|
||||
|
||||
networkConnection?.addEventListener("change", handleConnectionChange);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("online", handleOnline);
|
||||
window.removeEventListener("offline", handleOffline);
|
||||
networkConnection?.removeEventListener("change", handleConnectionChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return state;
|
||||
}
|
Loading…
Reference in New Issue
Block a user