add networkhook for network event

This commit is contained in:
Kamal Raj Sekar 2023-12-19 12:37:34 +00:00
parent 63b3ad2d57
commit f05cf9426f

View 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;
}