Skip to content

Instantly share code, notes, and snippets.

@andreigec
Created December 10, 2020 23:40
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 andreigec/e35393537738497b3dd1109450f02189 to your computer and use it in GitHub Desktop.
Save andreigec/e35393537738497b3dd1109450f02189 to your computer and use it in GitHub Desktop.
useNetworkConnectionType typescript
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