Skip to content

Instantly share code, notes, and snippets.

@exiguus
Created October 25, 2020 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exiguus/aa5691b941caba6f4150c2c73000e5c6 to your computer and use it in GitHub Desktop.
Save exiguus/aa5691b941caba6f4150c2c73000e5c6 to your computer and use it in GitHub Desktop.
NetworkInfo Hook
import { useState, useEffect } from 'react'
// Network Information API
// NetworkInfo https://wicg.github.io/netinfo/
// https://caniuse.com/netinfo
enum ConnectionType {
'bluetooth',
'cellular',
'ethernet',
'mixed',
'none',
'other',
'unknown',
'wifi',
'wimax',
}
enum EffectiveConnectionType {
'2g',
'3g',
'4g',
'slow-2g',
}
type NetworkInformation = {
readonly type?: keyof typeof ConnectionType
readonly effectiveType: keyof typeof EffectiveConnectionType
readonly saveData: boolean
readonly downlink: number
readonly downlinkMax?: number
readonly rtt: number
onchange: Function | null
}
interface NavigatorConnection extends Navigator {
readonly connection: NetworkInformation & EventTarget
}
type NetworkTypes = {
online: boolean
connection: NetworkInformation
}
function useNetwork(): NetworkTypes {
const connectionLegacy: NetworkInformation = {
type: 'unknown',
effectiveType: '4g',
saveData: false,
downlink: 3.45,
downlinkMax: 3.5,
rtt: 50,
onchange: null,
}
const [network, setNetwork] = useState({
online: window.navigator.onLine || true,
connection:
(window.navigator as NavigatorConnection).connection || connectionLegacy,
})
const updateNetwork = (): void => {
setNetwork({
online: window.navigator.onLine || true,
connection:
(window.navigator as NavigatorConnection).connection ||
connectionLegacy,
})
}
useEffect(() => {
const navigator = window.navigator as NavigatorConnection
navigator.connection?.addEventListener('change', updateNetwork)
window.addEventListener('offline', updateNetwork)
window.addEventListener('online', updateNetwork)
return (): void => {
navigator.connection?.removeEventListener('change', updateNetwork)
window.removeEventListener('offline', updateNetwork)
window.removeEventListener('online', updateNetwork)
}
})
return network
}
export default useNetwork
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment