Skip to content

Attaching Any other listener (firebase auth) into RootRouter file drops off Location, ActivityChange, MotionChange listeners  #908

@amitbravo

Description

@amitbravo

Your Environment

  • Plugin version: 3.3.2
  • Platform: iOS or Android : iOS
  • OS version: Catalina 10.15.1
  • Device manufacturer / model: iPhone SE + Macbook Pro
  • React Native version (react-native -v): "0.61.2",
  • Plugin config
  BackgroundGeolocation.ready({
    // Geolocation Config
    desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
    distanceFilter: 10,
    // Activity Recognition
    stopTimeout: 1,
    // Application config
    debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
    logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
    stopOnTerminate: true   // <-- Allow the background-service to continue tracking when user closes the app.
  }, (state) => {
    console.log("- BackgroundGeolocation is configured and ready: ", state.enabled);

    if (!state.enabled) {
      ////
      // 3. Start tracking!
      //
      // BackgroundGeolocation.start(function() {
      //   console.log("- Start success");
      //   this.setState({ start: true })
      // });
    }
    BackgroundGeolocation.getCurrentPosition({ sample: 1 },location =>  {
      //Toast.show("Ready to shoot");
      console.log('getCurrentPosition location',location)
      var getAustralianUnixAndDate = this.getAustralianUnixAndDate();
      firebase.firestore().collection('v2drivers').doc(this.state.currentUser)
      .set({
        currentPosLat: location.coords.latitude,
        currentPosLong: location.coords.longitude,
        currentPosTime: getAustralianUnixAndDate.unix,
        currentPosTimeHuman: getAustralianUnixAndDate.date,
        currentPosTimeIndia: Moment().format('DD-MM-YYYY hh:mm:ss a') //Dont need it later
      }, { merge: true })
      .then(()=> {
          console.log('getCurrentPosition location updated on server')
      }).catch(err =>{
          console.log('getCurrentPosition location update error',err)
      })

        self.setState({
            region : {
              latitude: Number(location.coords.latitude),
              longitude: Number(location.coords.longitude),
              latitudeDelta: self.state.LATITUDE_DELTA,
              longitudeDelta: self.state.LONGITUDE_DELTA
            } ,
            coordinate: {
              latitude: Number(location.coords.latitude),
              longitude: Number(location.coords.longitude),
              latitudeDelta: self.state.LATITUDE_DELTA,
              longitudeDelta: self.state.LONGITUDE_DELTA
            },
            showMap: true,
            disableEverything: false
        }, ()=>{
        console.log('everything good to go',self.state.showMap)
       })
    });
  });

Expected Behavior

All registered all Listeners and working fine if I do not add an event listeners into
Root Router file.

Actual Behavior

I have 4 files

  1. index.js
  2. App/RootRouter.js
  3. App/ExpLogin.js
  4. App/ExpHome.js //where BackgroundGeolocation configed and starts

index.js

import {AppRegistry} from 'react-native';

import App from './App/RootRouter';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

App/RootRouter.js


import React, {
  Component,
} from "react";
import {
  StyleSheet,
  Text,
  View,
  StatusBar,
  TouchableOpacity,
  AppState
} from "react-native";
import {
  Scene,
  Router,
  Actions,
  Tabs,
  Drawer,
  Stack
} from "react-native-router-flux";




import firebase from 'react-native-firebase'

import ExpLogin from './ExpLogin'
import ExpHome from './ExpHome'



export default class RootRouter extends Component {


  constructor(props) {
    super(props);
    this.state = {
    logged: false,
    loading: true,
    menuStyle: 0,
    connection: null,
    prefix: null,
    appState: AppState.currentState,
    }

  }

  componentWillUnmount() {
    if (this.unsubscribe) this.unsubscribe();
  }


   componentDidMount() {
     const self = this;

      // **this cause the trouble** 
     // firebase.auth().onAuthStateChanged(user => {
     //    console.log('user',user)
     //     if(user) {
     //         self.setState({
     //           logged: true
     //         });
     //     }else{
     //         self.setState({
     //           logged: false
     //         })
     //     }
     // });


  }



        render() {

        return (
          <View style={{ flex: 1 }}>
          <StatusBar barStyle="light-content"  />
          <Router titleStyle={{ fontSize: 17, fontWeight: 'normal' }} key="router" tintColor="white" >


          <Scene key="superroot" hideNavBar navigationBarStyle={styles.headerBarStyle}>

                  <Scene initial={this.state.logged}>
                        <Scene key="exphome"  component={ExpHome} title="Home" style={{backgroundColor: '#FFFFFF'}} onLeft={Actions.pop} navigationBarStyle={styles.headerBarStyle} renderRightButton={this._renderRightButton}  />
                  </Scene>


                  <Scene initial={!this.state.logged}>
                        <Scene key="explogin" component={ExpLogin} title="Login" style={{backgroundColor: '#FFFFFF'}} onLeft={Actions.pop} navigationBarStyle={styles.headerBarStyle} renderRightButton={this._renderRightButton}  />
                  </Scene>


            </Scene>
          </Router>


          </View>
        );
      }

}

const styles = StyleSheet.create({
  container: {
    flex: 1, backgroundColor: "transparent", justifyContent: "center",
    alignItems: "center"

  },
  /*
  headerBarStyle: {
    backgroundColor: "rgba(0, 145, 234, 1)"
  },
  */
  /*ORANGE ****/
  headerBarStyle: {
    backgroundColor: "#F29A00",

  },

  tabBarSelectedItemStyle: {
    backgroundColor: "rgba(0, 145, 234, 1)",
  },
  leftButtonTextStyle:{
    color: '#FFFFFF'
  },

  scene: {
    backgroundColor: '#F5FCFF',
    shadowOpacity: 1,
    shadowRadius: 3,
  },
});

App/ExpHome.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

 import React, { Component } from 'react';
 import {
   AppRegistry,
   StyleSheet,
   Text,
   View,
   TouchableOpacity,
   Dimensions,
   Platform,
   ImageBackground,
   TextInput,
   SafeAreaView,
   Image,
   ActivityIndicator,
   ScrollView,
   FlatList,
   YellowBox,
   Alert
 } from 'react-native';
 import Geocoder from 'react-native-geocoding';

 import * as RNLocalize from "react-native-localize";
 import {Actions} from 'react-native-router-flux';
 import _ from 'lodash';
 import firebase from 'react-native-firebase';
 //import DatePicker from 'react-native-datepicker'
 import Icon from "react-native-vector-icons/MaterialIcons";
 import EvilIcons from "react-native-vector-icons/EvilIcons";

 import MaterialIcon from "react-native-vector-icons/MaterialCommunityIcons";
 import ActionSheet from 'react-native-action-sheet';
 import call from 'react-native-phone-call';
 //import Share from 'react-native-share';
 import axios from 'axios'
 //import { getAppstoreAppVersion } from "react-native-appstore-version-checker";
 import DeviceInfo from 'react-native-device-info'
 import Modal from "react-native-modal"
 import MapView, { PROVIDER_GOOGLE, AnimatedRegion, Animated, Marker } from 'react-native-maps';
 //import Geolocation from 'react-native-geolocation-service';
 import RNAndroidLocationEnabler from 'react-native-android-location-enabler';
 import MapViewDirections from 'react-native-maps-directions';
 import Moment from 'moment'
 import MomentTimeZone from 'moment-timezone'
 import Toast from 'react-native-simple-toast';
 import SlidingUpPanel from 'rn-sliding-up-panel';
 import CountDown from 'react-native-countdown-component';
 import Spinner from 'react-native-loading-spinner-overlay';
 import { SwipeListView } from 'react-native-swipe-list-view';

 import BackgroundGeolocation from "react-native-background-geolocation";


 const os_type = Platform.OS;

 Geocoder.init("************************************");
 const PAGE_WIDTH = Dimensions.get('window').width;
 const PAGE_HEIGHT = Dimensions.get('window').height;
 const ASPECT_RATIO = PAGE_WIDTH / PAGE_HEIGHT;

 const {width, height, scale} = Dimensions.get("window");

 const ROOT_URL = 'https://*****************.cloudfunctions.net'

 import * as AddCalendarEvent from 'react-native-add-calendar-event';



export default class App extends Component {

  constructor(props) {
		super(props);
      this.state = {
        loading: false,
        msg: [],
        region: {
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.015,
          longitudeDelta: 0.0121,
        },
        coordinate: {
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.015,
          longitudeDelta: 0.0121,
        },

        LATITUDE_DELTA: 0.015,
        LONGITUDE_DELTA: 0.0121,

        alllogs: null,
        tripwise: false,
        start: false,
        counter: 0,
        LastTriggerat: ''

      }

      this.onLocation = this.onLocation.bind(this);
      this.onError = this.onError.bind(this);
      this.onActivityChange = this.onActivityChange.bind(this);
      this.onProviderChange = this.onProviderChange.bind(this);
      this.onMotionChange = this.onMotionChange.bind(this);

    }

  componentWillUnmount() {
      BackgroundGeolocation.removeListeners();
  }


    async componentDidMount(){

      const self = this;

      var currentUser = firebase.auth().currentUser
      console.log('currentUser',currentUser.uid)

      if ( currentUser !== null && typeof currentUser._user !== 'undefined' && currentUser._user.uid !== 'undefined' && currentUser._user.uid !== null) {
            this.setState({ currentUser: currentUser._user.uid  })
            firebase.firestore().collection('v2drivers').doc(currentUser._user.uid).set({ onDuty: false }, { merge: true });

            firebase.messaging().getToken()
            .then( (pushToken) => {
                  firebase.firestore().collection('v2drivers').doc(currentUser._user.uid).set({pushToken }, { merge: true });
            })

            firebase.auth().currentUser.getIdToken()
            .then( (idToken) => {
                firebase.firestore().collection('v2drivers').doc(currentUser._user.uid).set({idToken }, { merge: true });
            })

            firebase.messaging().subscribeToTopic('all');
            firebase.messaging().subscribeToTopic('drivers');
      }
      else {
        firebase.auth().signOut()
      }


      firebase.firestore().collection('demo').limit(10).get()
      .then(querySnapshot => {
                var alllogs = []
                querySnapshot.docs.map(function(doc) {
                    if (doc.exists){
                      alllogs.push({ ...doc.data(), id: doc.id });
                    }
                })
                this.setState({ alllogs })
      })
      .catch(error => {
          console.log('error ',error)
      })






      // This handler fires whenever bgGeo receives a location update.
      BackgroundGeolocation.onLocation(this.onLocation, this.onError);

      // This handler fires when movement states changes (stationary->moving; moving->stationary)
      BackgroundGeolocation.onMotionChange(this.onMotionChange);

      // This event fires when a change in motion activity is detected
      BackgroundGeolocation.onActivityChange(this.onActivityChange);

      // This event fires when the user toggles location-services authorization
      BackgroundGeolocation.onProviderChange(this.onProviderChange);

      ////
      // 2.  Execute #ready method (required)
      //
      BackgroundGeolocation.ready({
        // Geolocation Config
        desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
        distanceFilter: 10,
        // Activity Recognition
        stopTimeout: 1,
        // Application config
        debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
        logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
        stopOnTerminate: true   // <-- Allow the background-service to continue tracking when user closes the app.
      }, (state) => {
        console.log("- BackgroundGeolocation is configured and ready: ", state.enabled);

        if (!state.enabled) {
          ////
          // 3. Start tracking!
          //
          // BackgroundGeolocation.start(function() {
          //   console.log("- Start success");
          //   this.setState({ start: true })
          // });
        }
        BackgroundGeolocation.getCurrentPosition({ sample: 1 },location =>  {
          //Toast.show("Ready to shoot");
          console.log('getCurrentPosition location',location)
          var getAustralianUnixAndDate = this.getAustralianUnixAndDate();
          firebase.firestore().collection('v2drivers').doc(this.state.currentUser)
          .set({
            currentPosLat: location.coords.latitude,
            currentPosLong: location.coords.longitude,
            currentPosTime: getAustralianUnixAndDate.unix,
            currentPosTimeHuman: getAustralianUnixAndDate.date,
            currentPosTimeIndia: Moment().format('DD-MM-YYYY hh:mm:ss a') //Dont need it later
          }, { merge: true })
          .then(()=> {
              console.log('getCurrentPosition location updated on server')
          }).catch(err =>{
              console.log('getCurrentPosition location update error',err)
          })

            self.setState({
                region : {
                  latitude: Number(location.coords.latitude),
                  longitude: Number(location.coords.longitude),
                  latitudeDelta: self.state.LATITUDE_DELTA,
                  longitudeDelta: self.state.LONGITUDE_DELTA
                } ,
                coordinate: {
                  latitude: Number(location.coords.latitude),
                  longitude: Number(location.coords.longitude),
                  latitudeDelta: self.state.LATITUDE_DELTA,
                  longitudeDelta: self.state.LONGITUDE_DELTA
                },
                showMap: true,
                disableEverything: false
            }, ()=>{
            console.log('everything good to go',self.state.showMap)
           })
        });
      });



      //push


      this.messageListener = firebase.messaging().onMessage((message) => {
           // Process your message as required
           //console.log("is this new f**ing problem ?? message",message);
           //firebase.notifications().displayNotification(message);

       });

       this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
           //console.log('Dude, onNotificationDisplayed',notification)
       });


      this.notificationListener = firebase.notifications().onNotification(async (notification: Notification) => {

        const localnotification = new firebase.notifications.Notification({
                 sound: 'default',
                 show_in_foreground: true,
                 local_notification: true,
                 priority: 'high'
        })
        .setNotificationId(notification.notificationId)
        .setTitle(notification.title)
        .setSubtitle(notification.subtitle)
        .setBody(notification.body)
        .setData(notification.data);
        localnotification.android.setPriority(firebase.notifications.Android.Priority.High) /// set to High
        localnotification.android.setChannelId("teamcide")  ///for android 8.0 and above
        const channel = new firebase.notifications.Android.Channel(
          "daily",
          "Reminders",
          firebase.notifications.Android.Importance.High
        ).setDescription("Reminds you....");
        firebase.notifications().android.createChannel(channel);
         firebase.notifications().displayNotification(localnotification)
    });


     this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
         const action = notificationOpen.action;
         const notification: Notification = notificationOpen.notification;
         //console.log('Dude, onNotificationOpened',notification)
         //console.log('notification.data =>',notification.data)
         if( notification.data.type === 'notifySuccessJob'  ){
           //console.log('redirect it please notificationOpenedListener')
             //Actions['writenotice']({ prefix: this.state.prefix, itemID: notification.data.id, push: true });
             //Actions._exphome({ notifySuccessJob: true })
             if (currentUser._user.uid !== null){
               this.downloadJobsList(currentUser._user.uid)
             }
             this.setState({
               tab_selectedMap: false,
               tab_selectedAlert: false,
               tab_selectedJobs: true,
               tab_selectedSetting: false
             })
         }
         else if ( notification.data.type === 'newJob' ){
           this.setState({
             tab_selectedMap: false,
             tab_selectedAlert: true,
             tab_selectedJobs: false,
             tab_selectedSetting: false
           })
         }
     });


     firebase.notifications().getInitialNotification()
       .then((notificationOpen: NotificationOpen) => {
         if (notificationOpen) {
           const action = notificationOpen.action;
           const notification: Notification = notificationOpen.notification;
           if( notification.data.type === 'notifySuccessJob'  ){
             //console.log('redirect it please from getInitialNotification')
               //Actions._exphome({ notifySuccessJob: true })
               if (currentUser._user.uid !== null){
                 this.downloadJobsList(currentUser._user.uid)
               }
               this.setState({
                 tab_selectedMap: false,
                 tab_selectedAlert: false,
                 tab_selectedJobs: true,
                 tab_selectedSetting: false
               })
           }
           else if ( notification.data.type === 'newJob' ){
             this.setState({
               tab_selectedMap: false,
               tab_selectedAlert: true,
               tab_selectedJobs: false,
               tab_selectedSetting: false
             })
           }
         }
    });




    }


    onLocation(location) {
          console.log('[location] -', location);
          const self = this
          //timestamp

          self.setState({
              region : {
                latitude: Number(location.coords.latitude),
                longitude: Number(location.coords.longitude),
                latitudeDelta: self.state.LATITUDE_DELTA,
                longitudeDelta: self.state.LONGITUDE_DELTA
              } ,
              coordinate: {
                latitude: Number(location.coords.latitude),
                longitude: Number(location.coords.longitude),
                latitudeDelta: self.state.LATITUDE_DELTA,
                longitudeDelta: self.state.LONGITUDE_DELTA
              },
              showMap: true,
              disableEverything: false
          }, ()=>{
          console.log('everything good to go',self.state.showMap)
         })


          // this.setState({
          //   latitude: location.coords.latitude,
          //   longitude: location.coords.longitude
          // })

            var tripwise = 'demo';
            if(this.state.tripwise){
              tripwise = 'tripwise'
            }

            var currentPosTimeHuman = Moment().format('DD-MM-YYYY hh:mm:ss a');

            firebase.firestore().collection(tripwise).add({
              extra: location,
              currentPosLat: location.coords.latitude,
              currentPosLong: location.coords.longitude,
              currentPosTime: Moment().format('X'),
              currentPosTimeHuman
              })
             .then(response =>{
              console.log('firebase triggered',response)
              //this.setState({ counter:  })



              this.setState((prevState, props) => {
                          return {counter: prevState.counter + 1};
                })
                this.setState({ triggeredLastAt: currentPosTimeHuman })

              //Toast.show('Triggered')
              }).catch(error => {
                console.log('error',error)
              })


              firebase.firestore().collection('democurrentlocation').doc('currentlocation')
              .set({
                extra: location,
                currentPosLat: location.coords.latitude,
                currentPosLong: location.coords.longitude,
                currentPosTime: Moment().format('X'),
                currentPosTimeHuman
                })




    }
    onError(error) {
      console.warn('[location] ERROR -', error);
    }
    onActivityChange(event) {
      console.log('[activitychange] -', event);  // eg: 'on_foot', 'still', 'in_vehicle'
    }
    onProviderChange(provider) {
      console.log('[providerchange] -', provider.enabled, provider.status);
    }
    onMotionChange(event) {
      console.log('[motionchange] -', event.isMoving, event.location);
    }





    getAustralianUnix(){
      var datetime = MomentTimeZone().tz('Australia/Sydney').format("DD-MM-YYYY HH:mm:ss")
      var thedate = Moment(datetime, 'DD-MM-YYYY HH:mm:ss').format("X");
      return thedate;
    }

    getAustralianUnixAndDate(){
      var date = MomentTimeZone().tz('Australia/Sydney').format("DD-MM-YYYY HH:mm:ss")
      console.log('the date',date)
      var unix = Moment(date, 'DD-MM-YYYY HH:mm:ss').format("X");
      console.log('the unix',unix)
      return { date,unix };
    }

   msgall(){
     console.log('this.state.msg',this.state.alllogs)
      var display = _.map(this.state.alllogs, (msg,index) =>{
            return (
                <Text style={{ fontSize: 15 }} key={index}>logged</Text>
              )
       })
       return display;
   }

   /*
     <Text style={{ fontSize: 15 }} key={index}>{msg}</Text>
   <MapView
   provider={PROVIDER_GOOGLE}
   region={this.state.region}
   style={{ width: 500, height: 500 }}
   />
   */

   toggle(){
     var tripwise = !this.state.tripwise
     this.setState({ tripwise })
   }

   stop(){
     var start = !this.state.start
     if (start){
       this.setState({ start }, ()=> {
            console.log('this.state.start=>',this.state.start)
         })
       BackgroundGeolocation.start()
       .then(()=>{
          Toast.show('BackgroundGeolocation Starts')
         }).catch(error => {
           Toast.show('F****up while Starts')
           })
     }else {
       this.setState({ start })
       BackgroundGeolocation.stop()
       .then(()=>{
          Toast.show('BackgroundGeolocation Stops')
         }).catch(error => {
           Toast.show('F****up while Stops')
           })
     }
   }

   _onRegionChangeComplete = (Region) => {
     console.log('_onRegionChangeComplete region',Region)
     this.setState({ region: Region, LATITUDE_DELTA: Region.latitudeDelta, LONGITUDE_DELTA: Region.longitudeDelta  })
   }

    render(){
      return (
          <SafeAreaView style={{ padding: 10 }}>
            <ScrollView>
              <Text>Hi Super {this.state.currentUser}</Text>
              <Text>Counter {this.state.counter} times ,  LastTriggerat: {this.state.triggeredLastAt}</Text>
              <Text>Start Status: {this.state.start ? 'True': 'False'} </Text>

              <MapView
                provider={PROVIDER_GOOGLE} // remove if not using Google Maps
                style={{  height: 300,
                  width: 400 }}
                region={this.state.region}
                onRegionChangeComplete={this._onRegionChangeComplete}
              >
              <Marker
               coordinate={this.state.coordinate}
               title = "my location"
             />
              </MapView>

              <View style={{ alignItems: 'center'  }} >
              <TouchableOpacity onPress={()=>this.toggle()} style={{ marginTop: 5, justifyContent: 'center', alignItems: 'center', width: 200, height: 30, backgroundColor: this.state.tripwise ? '#51c9a6' : 'orange' }}>
                <Text style={{ color: 'white' }}>Click to {this.state.tripwise ? 'Normal' : 'Follow'}</Text>
              </TouchableOpacity>
              </View>


              <View style={{ marginTop: 15, alignItems: 'center'  }} >
              <TouchableOpacity onPress={()=>this.stop()} style={{ marginTop: 5, justifyContent: 'center', alignItems: 'center', width: 200, height: 30, backgroundColor: this.state.start ? 'red' : '#51c9a6' }}>
                <Text style={{ color: 'white' }}>{this.state.start ? 'CLick to Stop': 'Click to Start'}</Text>
              </TouchableOpacity>
              </View>


            </ScrollView>
          </SafeAreaView>
        );
    }

}

Everthing is working great if I comment out following code in RootRouter.js file
Every listener reponse great

 firebase.auth().onAuthStateChanged(user => {
console.log('user',user)
 if(user) {
 self.setState({
   logged: true
 });
 }else{
  self.setState({
 logged: false
 })
 }
});

but not when I use this method , using this method cause following errors
Sending 'activity....' with no listeners registered.
Sending 'location' with no listeners registered.
etc..
Any Listeners related of BackgroundGeolocation does not work at all if I use the code , I also tried other methods too , in detailed RootRouter.js file as below , none of them worked.

Detailed Versioned with many experimental listeners that stopped listeners of BackgroundGeolocation as follows
Detailed RootRouter.js


import React, {
  Component,
} from "react";
import {
  StyleSheet,
  Text,
  View,
  StatusBar,
  TouchableOpacity,
  AppState
} from "react-native";
import {
  Scene,
  Router,
  Actions,
  Tabs,
  Drawer,
  Stack
} from "react-native-router-flux";




import firebase from 'react-native-firebase'

import ExpLogin from './exp_login'
import ExpHome from './exp_home'
import NewApp from './NewApp'

import DrawerContent from './DrawerContent';
import MenuIcon from '@images/menu.png';


export default class RootRouter extends Component {


  constructor(props) {
    super(props);
    this.state = {
    logged: false,
    loading: true,
    menuStyle: 0,
    connection: null,
    prefix: null,
    appState: AppState.currentState,
    }

    //this.onUserChanged  = this.onUserChanged.bind(this);
  }

  onUserChanged = (currentUser) => {
    console.log('currentUser',currentUser)
    if (currentUser) {
      console.log(currentUser.toJSON())
      this.setState({ logged: true })
    }
  }

  // onUserChanged(currentUser) {
  //   // console.log('currentUser',currentUser)
  //   // if (currentUser) {
  //   //   console.log('currentUser re baba',currentUser);
  //   //   console.log(currentUser.toJSON())
  //   //     this.setState({ logged: true })
  //   // }
  //   // else {
  //   //   console.log('user seems logout, redirect to login page')
  //   //   this.setState({ logged: false })
  //   // }
  // }

  componentWillUnmount() {
    if (this.unsubscribe) this.unsubscribe();
  }


   componentDidMount() {
     const self = this;

     var currentUser = firebase.auth().currentUser;
     //console.log('currentUser',currentUser.uid)

     if ( currentUser !== null && typeof currentUser._user !== 'undefined' && currentUser._user.uid !== 'undefined' && currentUser._user.uid !== null) {
       this.setState({ logged: true })
     }
     else {
       this.setState({ logged: false })
     }


     // firebase.auth().onAuthStateChanged(user => {
     //    console.log('user',user)
     //     if(user) {
     //         self.setState({
     //           logged: true
     //         });
     //     }else{
     //         self.setState({
     //           logged: false
     //         })
     //     }
     // });

     //this.unsubscribe = firebase.auth().onAuthStateChanged(this.onUserChanged);
     //this.unsubscribe = firebase.auth().onUserChanged(this.onUserChanged);



     firebase.messaging().requestPermission().then(() => {
       console.log('thanks')
     }) //firebase.messaging().requestPermission()
     .catch(error => {
           console.log("user rejected");
       });

       // firebase.messaging().onTokenRefresh((pushToken) => {
       //   console.log('Refreshed FCM token: ', pushToken);
       //     firebase.auth().onAuthStateChanged(user => {
       //         if(user !== null) {
       //           console.log('user>',user)
       //           //firebase.firestore().collection('users').doc(user.uid).set({pushToken }, { merge: true });
       //         }
       //     })
       // });

  }



        render() {

        return (
          <View style={{ flex: 1 }}>
          <StatusBar barStyle="light-content"  />
          <Router titleStyle={{ fontSize: 17, fontWeight: 'normal' }} key="router" tintColor="white" >


          <Scene key="superroot" hideNavBar navigationBarStyle={styles.headerBarStyle}>



                {/*
                <Drawer
                    initial={this.state.logged}
                    navigationBarStyle={styles.headerBarStyle}
                    key="Landing"
                    onExit={() => {
                      console.log('Drawer closed');
                    }}
                    onEnter={() => {
                      console.log('Drawer opened');
                    }}
                    contentComponent={DrawerContent}
                    drawerImage={MenuIcon}
                    drawerWidth={250}
                    title="Home"
                  >
                  <Scene key="exphome"  component={NewApp} title="Home" />
                  </Drawer>
                  */}



                  <Scene initial={this.state.logged}>
                        <Scene key="exphome"  component={NewApp} title="Home" style={{backgroundColor: '#FFFFFF'}} onLeft={Actions.pop} navigationBarStyle={styles.headerBarStyle} renderRightButton={this._renderRightButton}  />
                  </Scene>


                  <Scene initial={!this.state.logged}>
                        <Scene key="explogin" component={ExpLogin} title="Login" style={{backgroundColor: '#FFFFFF'}} onLeft={Actions.pop} navigationBarStyle={styles.headerBarStyle} renderRightButton={this._renderRightButton}  />
                  </Scene>


            </Scene>
          </Router>


          </View>
        );
      }

}

const styles = StyleSheet.create({
  container: {
    flex: 1, backgroundColor: "transparent", justifyContent: "center",
    alignItems: "center"

  },
  /*
  headerBarStyle: {
    backgroundColor: "rgba(0, 145, 234, 1)"
  },
  */
  /*ORANGE*/
  headerBarStyle: {
    backgroundColor: "#F29A00",

  },

  tabBarSelectedItemStyle: {
    backgroundColor: "rgba(0, 145, 234, 1)",
  },
  leftButtonTextStyle:{
    color: '#FFFFFF'
  },

  scene: {
    backgroundColor: '#F5FCFF',
    shadowOpacity: 1,
    shadowRadius: 3,
  },
});

Steps to Reproduce

  1. Any Listener in parent RootRouter file dropOff BackgroundGeolocation's listeners

firebase.auth().onAuthStateChanged(user => ....
is important as I login and logout it switches Views between Login View and DashboardView (ExpHome)
I can not avoid it putting in RootRouter file where it conflicts with BackgroundGeoLocation Listeners
however if I put in exphome.js (however there is no use of it here ) it does not conflict at all.

Debug logs

Screenshot 2019-11-28 at 2 22 32 PM
IMG_1006

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions