Created
March 8, 2022 11:56
-
-
Save agnel/3bbde39d949ac5437f551ec7feff1e38 to your computer and use it in GitHub Desktop.
useNetwork Hook in react
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
function getNetworkConnection() { | |
return ( | |
window.navigator.connection | |
); | |
} | |
function getNetworkConnectionInfo() { | |
const connection = getNetworkConnection(); | |
if (!connection) { | |
return {}; | |
} | |
return { | |
rtt: connection.rtt, | |
type: connection.type, | |
saveData: connection.saveData, | |
downLink: connection.downLink, | |
downLinkMax: connection.downLinkMax, | |
effectiveType: connection.effectiveType, | |
}; | |
} | |
function useNetwork() { | |
const [state, setState] = useState(() => { | |
return { | |
since: undefined, | |
online: navigator.onLine, | |
...getNetworkConnectionInfo(), | |
}; | |
}); | |
useEffect(() => { | |
const handleOnline = () => { | |
setState((prevState) => ({ | |
...prevState, | |
online: true, | |
since: new Date().toString(), | |
})); | |
}; | |
const handleOffline = () => { | |
setState((prevState) => ({ | |
...prevState, | |
online: false, | |
since: new Date().toString(), | |
})); | |
}; | |
const handleConnectionChange = () => { | |
setState((prevState) => ({ | |
...prevState, | |
...getNetworkConnectionInfo(), | |
})); | |
}; | |
window.addEventListener('online', handleOnline); | |
window.addEventListener('offline', handleOffline); | |
const connection = getNetworkConnection(); | |
connection?.addEventListener('change', handleConnectionChange); | |
return () => { | |
window.removeEventListener('online', handleOnline); | |
window.removeEventListener('offline', handleOffline); | |
connection?.removeEventListener('change', handleConnectionChange); | |
}; | |
}, []); | |
return state; | |
} | |
export default useNetwork; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Somehow it doesn't work in typescript.
The connection object doesn't have rrt and other variables.