I tried to use the NetInfo example from the expo docs: https://docs.expo.io/versions/latest/sdk/netinfo/
When I am compiling for web, the compiling fails with
TypeError: NetInfo.addEventListener is not a function
(anonymous function)
..components/OfflineFullScreen.jsx:22
21 |
> 22 | const unsubscribe = NetInfo.addEventListener((state) => {
| ^ 23 | console.log('Connection type', state.type);
24 | console.log('Is connected?', state.isConnected);
25 | });
even though the docs state that it should be supported.
My screen looks like that:
import React, { useEffect, useState } from 'react';
import {
View, Text, StyleSheet, ActivityIndicator,
} from 'react-native';
// import NetInfo from '@react-native-community/netinfo';
import * as NetInfo from '@react-native-community/netinfo';
const OfflineNotice = () => {
const [connected, setConnected] = useState(true);
useEffect(() => {
/* const unsubscribe = NetInfo.addEventListener((state) => {
if (state.isConnected) {
setConnected(true);
} else {
setConnected(false);
}
}); */
const unsubscribe = NetInfo.addEventListener((state) => {
console.log('Connection type', state.type);
console.log('Is connected?', state.isConnected);
});
return unsubscribe();
}, []);
if (!connected) { // if not connected return an full sized overlay
return (
<View style={styles.offlineContainer}>
<ActivityIndicator size="large" color="darkorange" />
<Text style={styles.offlineText}>No Internet Connection</Text>
<Text style={styles.offlineText}>Trying to reconnect ...</Text>
</View>
);
}
return null;
};
const styles = StyleSheet.create({
offlineContainer: {
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
position: 'absolute',
left: 0,
top: 0,
opacity: 0.85,
backgroundColor: 'black',
width: '100%',
height: '100%',
zIndex: 100,
},
offlineText: {
color: '#fff',
marginTop: '3%',
},
});
export default OfflineNotice;
Any idea what I am doing wrong? Is it maybe a bug, as expo-web is still beta?
I'm using Expo SDK 37, @react-native-community/netinfo@4.6.0,
In React Native Web an outdated Netinfo version is used. This could be solved by adding a polyfill like the code below.
import { useEffect, useState, useCallback } from 'react';
import { Platform } from 'react-native';
import NetInfo from 'react-native-web/dist/exports/NetInfo';
function useOldNetInfo() {
const [netInfo, setNetInfo] = useState<NetInfo.NetInfoState>({});
const [isConnected, setIsConnected] = useState<boolean>(true);
const onInfo = useCallback((data) => {
setNetInfo({ ...data, isConnected });
}, [isConnected]);
useEffect(() => {
NetInfo.getConnectionInfo().then(onInfo);
NetInfo.isConnected.fetch().then(setIsConnected);
return NetInfo.addEventListener('connectionChange', onInfo).remove;
}, [onInfo]);
return netInfo;
}
export default Platform.select({
web: useOldNetInfo,
ios: CommunityNetInfo.useNetInfo,
android: CommunityNetInfo.useNetInfo,
});
Github Issue: https://github.com/expo/expo/issues/8070