user10396319
user10396319

Reputation: 33

NetInfo.addEventListener not working in react-native

I am using NetInfo component in react-native to detect the state of network and keep listen to the network using NetInfo.addEventListener() in react-native.But when I change the network connection from wifi to internet or viceversa,state is not listening. My code is as follows:

  import React, {Component, PropTypes} from 'react';

   import {
   Platform,
   View,
   Text,
   Image,
    StyleSheet,
   AsyncStorage, 
   BackHandler,
   StatusBar  ,
   NetInfo,
  Alert
 } from 'react-native';
 const iconBasePath = './../../assets/images/'
   import App from './../../App'
  import EventsList from './EventsList'
  import LoginScreen from './LoginScreen'
 import Storage from 'react-native-storage'
 import EventDetails from './EventDetails'
 import DeviceInfo from 'react-native-device-info';
 import RegisterDeviceApiMgr from './../ApiMgrs/RegisterDeviceApiMgr'
   import * as firebase from 'firebase'

 import { GoogleAnalyticsTracker } from 'react-native-google- 
 analytics-bridge'
 import ComponentBase from '../ComponentBase';
import FlashMessage from "react-native-flash-message";
// import  { Firebase } from 'react-native-firebase'
import '@firebase/messaging';
import firebaseNotification from 'react-native-firebase';
import RegisterScreen from './RegisterScreen'
let tracker = new GoogleAnalyticsTracker('*******')

var config = {
  apiKey: "*******",
  authDomain: "*****",
  databaseURL: "****",
  projectId: "*******"
  }
  firebase.initializeApp(config);

 export default  class SplashScreen extends ComponentBase {

  constructor(props){
    super(props);

    this.state = {
        timePassed: false,
        deviceId:"",
        id:"",
        index:2,
    };
}

componentWillUnmount() {
    // this.notificationDisplayedListener();
    // this.notificationListener();
    // this.notificationOpenedListener();
    // this.onTokenRefreshListener();

}
async checkFirebase(){
    console.log("inside checkfirebase 123");
    try{
        const enabled = await firebaseNotification.messaging().hasPermission();
        if (enabled) {
            console.log("inside  enabled");

            // user has permissions
            // this.registerFbCloudMessagingListener()
            this.getToken();

        } else {
            // user doesn't have permission
            console.log("inside else  enabled");

            this.requestFbPermission()
        }

    }
    catch(error){
        console.log("checkfirebase",error.message);
    }

}
async requestFbPermission(){
    try {
        let permission = await firebaseNotification.messaging().requestPermission();
        if (permission) {
            console.log("inside permission  ");

            this.checkFirebase();
        }
        // User has authorised
    } catch (error) {
        console.log("inside error  permission",error.message);

        // User has rejected permissions
    }
}


async getToken(){
    try{
        let token = await firebaseNotification.messaging().getToken();
        console.log("FIREBASE TOKEN", token);
        const tokenSave = await AsyncStorage.setItem('tokenSave', token);

        // const deviceId = DeviceInfo.getUniqueID();
        //              this.setState({
        //                  deviceId:deviceId
        //              })
        //              this.registerDevice(token , deviceId);
    }
    catch(error){
        console.log("while getting token error",error.message);
    }


}

 async componentDidMount() {
       NetInfo.getConnectionInfo().then((connectionInfo) => {
    console.log('Initial, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
  });
  function handleFirstConnectivityChange(connectionInfo) {
    console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
    NetInfo.removeEventListener(
      'connectionChange',
      handleFirstConnectivityChange
    );
  }
  NetInfo.addEventListener(
    'connectionChange',
    handleFirstConnectivityChange
  );

    firebaseNotification.analytics().setCurrentScreen("SplashScreen");
    const value = await AsyncStorage.getItem('SignInStatus');
    // const userId = await 
    AsyncStorage.setItem("userId",this.state.id);
    // const deviceId = await 
   AsyncStorage.setItem('deviceId',this.state.deviceId);
    console.log("value issssssssssssssssssssssssss",value);
    firebaseNotification.notifications().getInitialNotification()
    .then((notificationOpen) => {
        console.log("received when app closed",notificationOpen);
      if (notificationOpen) {
          console.log("received notifi",notificationOpen);
        // App was opened by a notification
        // Get the action triggered by the notification being opened
         const data = notificationOpen.notification._data;
         console.log("received notifi event id",data.my_key);
         if(value =='true'){
         this.props.navigation.navigate('EventDetails',{eventId:data.my_key, index:this.state.index, lastScreen:'BaseScreen'})
        // Get information about the notification that was opened
         const notification = notificationOpen.notification;  
         console.log("received notification ",notification);
         } 
         else{
            this.props.navigation.navigate('LoginScreen'); 
        //  this.props.navigation.navigate('RegisterScreen'); 
         }
      }
      else{
        this.checkFirebase();
          console.log("time passed set")
          setTimeout( () => {
            this.setTimePassed();    
         }, 5000);

      }
    });
    // this.notification();
    tracker.trackScreenView('SplashScreen')
}

// registerDevice(token , deviceId){
//     let apiMgr = new RegisterDeviceApiMgr();
//     apiMgr.putDeviceData(token , deviceId)
//     .then((Data) => {
//         var deviceresponse = JSON.parse(Data._bodyInit)
//          console.log("SUcessssssssss Registering Device "+JSON.stringify(deviceresponse.user._id))
//          this.setState({
//              id:deviceresponse.user._id
//          })
//          this.setId(deviceresponse.user._id);
//         // this.props.navigation.navigate('EventDetails',{eventCode:this.state.EventCode ,eventId:this.state.eventId, index:this.state.indx,lastScreen:'UserData'})
//      })
//      .catch( (error) => {
//          console.log(error);
// if(error == 'TypeError: Network request failed'){
//   Alert.alert('Something went wrong', 'Kindly check if the device is connected to stable cellular data plan or WiFi.'); 
//  }

//      });
// }
// setId=async(deviceresponse)=>{
//     try{
//         console.log("user id",deviceresponse);
//         const userId = await AsyncStorage.setItem("userId",deviceresponse);
//         console.log("setting id is",this.state.id);

//     }
//     catch(error){
//         console.error(error.message);
//     }
// }

setTimePassed = async () =>{
    try {
        // console.log("userid and device id",this.state.id+" "+this.state.deviceId);
       const value = await AsyncStorage.getItem('SignInStatus');
    //    const userId = await AsyncStorage.setItem("userId",this.state.id);
    //    const deviceId = await AsyncStorage.setItem('deviceId',this.state.deviceId);
       console.log("value is",value);
       if (value == "true"){
          // alert(JSON.stringify(this.state.id))
          console.log("value present",value);
          this.props.navigation.navigate('EventsList')  
        }
        else {
           // alert(JSON.stringify(this.state.id))
           this.props.navigation.navigate('LoginScreen'); 
         //  this.props.navigation.navigate('RegisterScreen');
       }
        //    this.props.navigation.navigate('LoginScreen'); 

      } 

      catch (error) {
        console.log("value not present",error.message);

      }

 }
  render() {
       if(!this.state.timePassed){
        return(
            <View style = { styles.MainContainer }>
            <StatusBar
                   backgroundColor="#000080"
                   barStyle="light-content"/>

                <View style={styles.SplashScreen_RootView}>

                    <View style={styles.SplashScreen_ChildView}>

                        {/* Put all your components Image and Text here inside Child view which you want to show in Splash Screen. */}
                        <Image  source={require('./../../assets/NewWrapo.jpg')}
                        style={{width:'100%', height: '100%', resizeMode: 'contain'}} />

                    </View>

                </View>

            </View>
        )
    }

   }
 }


const styles = StyleSheet.create(
   {
    MainContainer:
    {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
  //          paddingTop: ( Platform.OS === 'ios' ) ? 20 : 0
    },

    SplashScreen_RootView:
    {
                justifyContent: 'center',
                flex:1,
  //            margin: 10,
                position: 'absolute',
                width: '100%',
                height: '100%',

      },

       SplashScreen_ChildView:
      {
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#1F0242',
            flex:1,
  //            margin: 20,
    },

    TouchableOpacity_Style:{

        width:25, 
        height: 25, 
        top:9, 
        right:9, 
        position: 'absolute'

    }
});

I am adding the above code in componentDidMount() method.Here,I am only able to see the output for only NetInfo.getConnectionInfo() ,but not for NetInfo.addEventListener().Please help me out.

Upvotes: 2

Views: 5111

Answers (2)

Mukeyii
Mukeyii

Reputation: 580

At first: Try to add the EventListener before your component mounts (componentWillMount) and remove it before unmounting (componentWillUnmount).

Another point is: Why should your component update and print your console.log, if there is no state change? Your handleConnectionChange method does nothing. Change that first and load the value (isConnected) into your state.

Upvotes: 1

JRK
JRK

Reputation: 3904

Check you have the correct permissions..

Android:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Upvotes: 1

Related Questions