Skip to content

Instantly share code, notes, and snippets.

@ananth10
Last active March 3, 2021 08:24
Show Gist options
  • Save ananth10/b1405ed797ededaf4c78de839a8b89b3 to your computer and use it in GitHub Desktop.
Save ananth10/b1405ed797ededaf4c78de839a8b89b3 to your computer and use it in GitHub Desktop.
Detect network connection changes in react native
import React, { useEffect, useState } from 'react';
import { StyleSheet, View, Text, Alert } from 'react-native';
import NetInfo from '@react-native-community/netinfo'
let cellularGeneration=''
let signalStrength=100
let connectionType=''
const NetworkConnectionChange=()=>{
const [isNetworkConnected, setIsNetworkConnected] = useState(true)
const [showNetworkConnectionMessage, setShowNetworkConnectionMessage] = useState(false)
useEffect(() => {
let connectionDetails
const unsubscribe = NetInfo.addEventListener(state => {
if (state.isConnected) {
setIsNetworkConnected(true);
} else {
setIsNetworkConnected(false);
}
connectionDetails=state.details
connectionType=state.type
if(connectionType=='cellular'){
cellularGeneration=connectionDetails.cellularGeneration
} else if(connectionType=='wifi'){
signalStrength=connectionDetails.strength
}
});
return () => {
unsubscribe()
}
}, [isNetworkConnected]);
const isSlowNetworkConnection=()=>{
if((connectionType=='wifi' && signalStrength<50) || (connectionType=='cellular' && cellularGeneration=='2g')){
return true
}else{
return false
}
}
useEffect(() => {
let timer
if (isNetworkConnected) {
timer = setTimeout(() => {
setShowNetworkConnectionMessage(false)
}, 2000);
} else {
setShowNetworkConnectionMessage(true)
}
return () => clearTimeout(timer);
}, [isNetworkConnected]);
const getNetworkConnectionStyle = () => {
if (isNetworkConnected) {
return {
padding:5,
width: '100%',
fontSize: 14,
color: '#ffffff',
justifyContent: 'center',
alignSelf: 'center',
backgroundColor: 'green',
textAlign: 'center'
}
} else {
return {
padding: 5,
width: '100%',
fontSize:14,
color: '#ffffff',
justifyContent: 'center',
alignSelf: 'center',
backgroundColor: 'red,
textAlign: 'center'
}
}
}
const getNetworkStatusText = () => {
if (isNetworkConnected) {
return 'Back Online'
} else {
return 'No Connection'
}
}
return (
<View style={{ flex: 1 }}>
{showNetworkConnectionMessage && <Text style={getNetworkConnectionStyle()}>{getNetworkStatusText()}</Text>}
{isNetworkConnected && isSlowNetworkConnection() && <Text style={styles.slowConnection}>You have slow network connection</Text>}
<View>
)
}
const styles = StyleSheet.create({
slowConnection:{
padding: 5,
width: '100%',
fontSize: 14,
color: '#ffffff',
justifyContent: 'center',
alignSelf: 'center',
backgroundColor: 'blue',
textAlign: 'center'
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment