Created
December 10, 2020 23:40
-
-
Save andreigec/e35393537738497b3dd1109450f02189 to your computer and use it in GitHub Desktop.
useNetworkConnectionType typescript
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'; | |
type ConnectionType = 'slow' | '2g' | '3g' | '4g' | 'fast'; | |
const parseEffectiveType = ( | |
connectionType: string, | |
defaultConnectionType: ConnectionType, | |
): ConnectionType => { | |
if (!connectionType) { | |
return defaultConnectionType; | |
} | |
switch (connectionType) { | |
case 'slow-2g': | |
return 'slow'; | |
case '2g': | |
return '2g'; | |
case '3g': | |
return '3g'; | |
case '4g': | |
return '4g'; | |
default: | |
return defaultConnectionType; | |
} | |
}; | |
export const useNetworkConnectionType = ( | |
defaultConnectionType: ConnectionType = 'fast', | |
): ConnectionType => { | |
const isSupported = !!(navigator as any)?.connection?.effectiveType; | |
const [connectionType, setNetworkStatus] = useState( | |
parseEffectiveType( | |
(navigator as any)?.connection?.effectiveType, | |
defaultConnectionType, | |
), | |
); | |
useEffect(() => { | |
if (isSupported) { | |
const { connection } = navigator as any; | |
const updateConnectionType = () => { | |
setNetworkStatus( | |
parseEffectiveType(connection.effectiveType, defaultConnectionType), | |
); | |
}; | |
connection.addEventListener('change', updateConnectionType); | |
return () => { | |
connection.removeEventListener('change', updateConnectionType); | |
}; | |
} | |
return () => {}; | |
}, [defaultConnectionType, isSupported]); | |
return connectionType; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment