Deep linking - getInitialURL and subscribe not being called - react-native

Current Behavior
Currently trying to get getInitialURL and subscribe to work, but they are just no tbeing called
import * as React from 'react';
import {DefaultTheme, NavigationContainer} from '#react-navigation/native';
import AuthStack from '../features/auth/AuthStack';
import {navigationRef} from './RootNavigation';
import {gestureHandlerRootHOC} from 'react-native-gesture-handler';
import messaging from '#react-native-firebase/messaging';
import {Linking} from 'react-native';
const Navigation = () => {
const routeNameRef = React.useRef();
const MyTheme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
background: 'rgba(0,0,0,0)',
},
};
const deepLinksConf = {
initialRouteName: 'Dashboard',
screens: {
Dashboard: {
initialRouteName: 'Tasks',
screens: {
Tasks: {
initialRouteName: 'TasksIndex',
screens: {
TasksIndex: 'TasksIndex',
TaskView: 'TaskView/:id',
},
},
},
},
queue: 'queue',
},
};
const linking = {
prefixes: ['verbleif://'],
config: deepLinksConf,
async getInitialURL() {
console.log('getInitialURL');
// Check if app was opened from a deep link
const url = await Linking.getInitialURL();
console.log('just initial');
if (url != null) {
return url;
}
// Check if there is an initial firebase notification
const message = await messaging().getInitialNotification();
console.log('using firebase message link');
// Get deep link from data
// if this is undefined, the app will open the default/home page
return message?.data?.llink;
},
subscribe(listener) {
console.log('subscirbe');
const onReceiveURL = ({url}: { url: string }) => listener(url);
// Listen to incoming links from deep linking
Linking.addEventListener('url', onReceiveURL);
// Listen to firebase push notifications
const unsubscribeNotification = messaging().onNotificationOpenedApp(
(message) => {
console.log('onNotificationOpenedApp', message);
const url = message?.data?.link;
if (url) {
// Any custom logic to check whether the URL needs to be handled
// Call the listener to let React Navigation handle the URL
listener(url);
}
},
);
return () => {
// Clean up the event listeners
Linking.removeEventListener('url', onReceiveURL);
unsubscribeNotification();
};
},
};
return (
<NavigationContainer linking={linking} theme={MyTheme} ref={navigationRef}
// onReady={() => routeNameRef.current = navigationRef.current.getCurrentRoute().name}
// onStateChange={async () => {
// const previousRouteName = routeNameRef.current;
// const currentRouteName = navigationRef.current.getCurrentRoute().name;
//
// if (previousRouteName !== currentRouteName) {
// // The line below uses the expo-firebase-analytics tracker
// // https://docs.expo.io/versions/latest/sdk/firebase-analytics/
// // Change this line to use another Mobile analytics SDK
// await analytics().logScreenView({
// screen_name: currentRouteName,
// screen_class: currentRouteName,
// });
// }
//
// // Save the current route name for later comparision
// routeNameRef.current = currentRouteName;
// }}
>
<AuthStack/>
</NavigationContainer>
);
};
export default gestureHandlerRootHOC(Navigation);
Expected Behavior
The console logs to aleast appear
How to reproduce
Use the code above with the newest packages.
Your Environment
I am using react native CLI and just updated everything to newest

Related

Audio and Video not working offline when using useNetInfo from netinfo

I've been battling a bug in my code for the last 4 days and would appreciate some pointers to get me going in the right directions. Component is working fine as long as there is internet connection, but if there is no internet connection, audios and videos are not playing, only thumbnail present.
I'm using netInfo's NetInfo.fetch() to check for connection. If there is connection, I'm refetching data to check for any updates to student assignments.
I'm using expo-av for playing audio/video files (v10.2.1). I'm also using useQuery hook from react-query to fetch data about audio and video files (like url etc.) My video player component is something like this:
Video Player:
import React, {
forwardRef,
ForwardRefRenderFunction,
useCallback,
useImperativeHandle,
useRef
} from 'react';
import { Platform } from 'react-native';
import Orientation from 'react-native-orientation-locker';
import { Audio, Video, VideoFullscreenUpdateEvent, VideoProps } from 'expo-av';
const Player: ForwardRefRenderFunction<
Video | undefined,
VideoProps
> = (props, ref) => {
const innerRef = useRef<Video>(null);
const orientation = useCallback<
(event: VideoFullscreenUpdateEvent) => void
>(
(event) => {
if (Platform.OS === 'android') {
if (
event.fullscreenUpdate === Video.FULLSCREEN_UPDATE_PLAYER_DID_PRESENT
) {
Orientation.unlockAllOrientations();
} else if (
event.fullscreenUpdate === Video.FULLSCREEN_UPDATE_PLAYER_DID_DISMISS
) {
Orientation.lockToPortrait();
}
}
props.onFullscreenUpdate?.(event);
},
[props]
);
useImperativeHandle(ref, () => {
if (innerRef.current) {
return innerRef.current;
}
return undefined;
});
return (
<Video
resizeMode="contain"
useNativeControls
ref={innerRef}
onLoad={loading}
{...props}
onFullscreenUpdate={orientation}
/>
);
};
export const VideoPlayer = forwardRef(Player);
Custom Hook:
For async state management, I'm using a custom react-query hook, that looks something like this (non-relevant imports and code removed):
import { useFocusEffect } from '#react-navigation/core';
import { useCallback } from 'react';
import NetInfo from '#react-native-community/netinfo';
export const useStudentAssignment = (
assignmentId: Assignment['id']
): UseQueryResult<Assignment, Error> => {
const listKey = studentAssignmentKeys.list({ assignedToIdEq: studentData?.id });
const queryClient = useQueryClient();
const data = useQuery<Assignment, Error>(
studentAssignmentKeys.detail(assignmentId),
async () => {
const { data: assignment } = await SystemAPI.fetchAssignment(assignmentId);
return Assignment.deserialize({
...assignment,
});
},
{
staleTime: 1000 * 60 * 30,
initialData: () => {
const cache= queryClient.getQueryData<Assignment[]>(listKey);
return cache?.find((assignment) => assignment.id === assignmentId);
},
initialDataUpdatedAt: queryClient.getQueryState(listKey)?.dataUpdatedAt,
}
);
useFocusEffect(
useCallback(() => {
NetInfo.fetch().then((state) => {
if (state.isConnected) {
data.refetch();
}
});
}, [data])
);
return data;
};
Component:
import React, { FC, useCallback, useEffect, useMemo, useRef } from 'react';
import { SafeAreaView } from 'react-native-safe-area-context';
import { StackScreenProps } from '#react-navigation/stack';
import { ROUTES } from 'enums/SMSRoutes';
import { StoreType } from 'enums/SMSStoreType';
import { useStudentAssignment } from 'hooks/Assignments/useStudentAssignment';
import { RootStackParamList } from 'navigators';
import { AssignmentViewer } from 'screens/AssignmentViewer';
type NavProps = StackScreenProps<
RootStackParamList,
ROUTES.ASSIGNMENT_VIEW
>;
export const AssignmentView: FC<NavProps> = ({
navigation,
route: {
params: { assignmentId }
}
}) => {
const assignmentQuery = useStudentAssignment(assignmentId);
const assignmentTracker = useStore(StoreType.AssignmentTracker);
const isDoneRef = useRef<boolean>(false);
const questions = assignmentQuery.data?.questions || [];
const activeQuestion = useMemo(() => {
return questions.filter((question) => question.active);
}, [questions]);
const onDone = useCallback(() => {
isDoneRef.current = true;
navigation.push(ROUTES.ASSIGNMENT_COMPLETED);
}, [navigation]);
useEffect(() => {
assignmentTracker.start(assignmentId);
return () => {
assignmentTracker.finish(isDoneRef.current);
};
}, []);
return (
<SafeAreaView>
<AssignmentViewer
questions={activeQuestion}
onDone={onDone}
isLoading={assignmentQuery.isLoading}
/>
</SafeAreaView>
);
};
What I'm trying to do here is that if internet connection is connected and the user navigates to the current view (which is used to view assignments), I'd like to refetch the data. Per the requirements, I can't use the staleTime property or any other interval based refetching.
Component is working fine if I don't refetch, or if internet connection is present. If connection isn't there, it doesn't play the cache'd audio/video.
If I take out the check for internet connection (remove netInfo), component display videos both offline and online. However, refetching fails due to no connectivity.
What should I change to make sure that data is refetched when connected and videos are played even if not connected to Internet?

Accessing push notification data while app is killed

I am trying to access push notification data with killed app.
I have been reading the docs and implemented the steps that are provided but still i don't get any data, it's like the push notification is not detected.
I am using:
"expo": "^42.0.0",
"expo-notifications": "~0.12.3",
The code is the following:
import { enableScreens } from 'react-native-screens'
import { NavigationContainer } from '#react-navigation/native';
import CarNavigator from './src/navigation/CarNavigator'
import { Alert } from 'react-native';
import React, { useState, useEffect, useRef } from 'react'
import * as Notifications from 'expo-notifications'
import Constants from 'expo-constants';
enableScreens();
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: true,
}),
});
export default function App() {
const [expoPushToken, setExpoPushToken] = useState('');
const [notification, setNotification] = useState(false);
const notificationListener = useRef();
const responseListener = useRef();
const registerForPushNotificationsAsync = async () => {
let token;
if (Constants.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
console.log('Failed to get push token for push notification!');
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
} else {
console.log('Must use physical device for Push Notifications');
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
return token;
}
useEffect(() => {
registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
setNotification(notification);
});
responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
Alert.alert('IN');
});
return () => {
Notifications.removeNotificationSubscription(notificationListener.current);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
/* END */
return (
<NavigationContainer>
<CarNavigator />
</NavigationContainer>
)
}
As per the documentation this part handles push notification data while app is killed as stated here:
https://docs.expo.dev/versions/latest/sdk/notifications/#listening-to-notification-events
responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
Alert.alert('IN');
});
When i send a push notification and start the app using that notification the Alert is not triggered, it's like the push notification is not detected.
I am testing this on android with a standalone apk build.
Anyone had this issue and managed to solve it?
Many thanks,
Trix

How to pass localization info from this.context in react component to its child consts?

I have implemented localization for React-native app according to this file as LocalizationContext.js:
import React from 'react';
import Translations, {DEFAULT_LANGUAGE} from '../constants/Translations';
import AsyncStorage from '#react-native-community/async-storage';
import * as RNLocalize from 'react-native-localize';
const APP_LANGUAGE = 'appLanguage';
export const LocalizationContext = React.createContext({
Translations,
setAppLanguage: () => {},
appLanguage: DEFAULT_LANGUAGE,
initializeAppLanguage: () => {},
});
export const LocalizationProvider = ({children}) => {
const [appLanguage, setAppLanguage] = React.useState(DEFAULT_LANGUAGE);
const setLanguage = language => {
Translations.setLanguage(language);
setAppLanguage(language);
AsyncStorage.setItem(APP_LANGUAGE, language);
};
const initializeAppLanguage = async () => {
const currentLanguage = await AsyncStorage.getItem(APP_LANGUAGE);
if (!currentLanguage) {
let localeCode = DEFAULT_LANGUAGE;
const supportedLocaleCodes = Translations.getAvailableLanguages();
const phoneLocaleCodes = RNLocalize.getLocales().map(
locale => locale.languageCode,
);
phoneLocaleCodes.some(code => {
if (supportedLocaleCodes.includes(code)) {
localeCode = code;
return true;
}
});
setLanguage(localeCode);
} else {
setLanguage(currentLanguage);
}
};
return (
<LocalizationContext.Provider
value={{
Translations,
setAppLanguage: setLanguage,
appLanguage,
initializeAppLanguage,
}}>
{children}
</LocalizationContext.Provider>
);
};
and it works fine in different screens but App.js file which is something like:
const MainTabs = createBottomTabNavigator(
{
Profile: {
screen: ProfileStack,
navigationOptions: {
// tabBarLabel: Translations.PROFILE_TAB,
},
},
HomePage: {
screen: HomeStack,
navigationOptions: {
tabBarLabel: Translations.HOME_TAB,
},
},
},
{
initialRouteName: 'HomePage'
},
},
);
export default class App extends Component {
// static contextType = LocalizationContext;
render() {
// const Translations = this.context.Translations;
// console.log(Translations.PROFILE_TAB);
return (
<LocalizationProvider>
<SafeAreaView style={{flex: 1}}>
<AppNavigator />
</SafeAreaView>
</LocalizationProvider>
);
}
}
I do access Translation in App component as you can find them in commented lines, but how can I pass related information to some const like tab titles? Translations.PROFILE_TAB is undefined.
I ended up changing this into a service.
Also I use redux and pass the store in to get user preferences and set them:
import * as RNLocalize from 'react-native-localize';
import { saveUserOptions } from '../actions/login';
import LocalizedStrings from 'react-native-localization';
export const DEFAULT_LANGUAGE = 'ar';
let _reduxStore;
function setStore(store){
_reduxStore = store
}
const _translations = {
en: {
WELCOME_TITLE: 'Welcome!',
STEP1: 'Step One',
SEE_CHANGES: 'See Your Changes',
CHANGE_LANGUAGE: 'Change Language',
LANGUAGE_SETTINGS: 'Change Language',
BACK: 'Back'
},
ar: {
WELCOME_TITLE: 'صباحك فُل!',
...
}
};
let translation = new LocalizedStrings(_translations);
const setAppLanguage = language => {
translation.setLanguage(language);
_reduxStore.dispatch(saveUserOptions('user_language',language))
};
const initializeAppLanguage = async () => {
const currentLanguage = _reduxStore.getState().login.user_language
if (!currentLanguage) {
let localeCode = DEFAULT_LANGUAGE;
const supportedLocaleCodes = translation.getAvailableLanguages();
const phoneLocaleCodes = RNLocalize.getLocales().map(
locale => locale.languageCode,
);
phoneLocaleCodes.some(code => {
if (supportedLocaleCodes.includes(code)) {
localeCode = code;
return true;
}
});
setAppLanguage(localeCode);
} else {
setAppLanguage(currentLanguage);
}
};
export default {
setStore,
translation,
setAppLanguage,
initializeAppLanguage
}
I need to first setup things in my top main component:
LocalizationService.setStore(store)
...
// add the below to componentDidMount by which time persisted stores are populated usually
LocalizationService.initializeAppLanguage()
where I need to get strings I do:
import LocalizationService from '../../utils/LocalizationService';
....
static navigationOptions = () => {
// return here was needed otherwise the translation didn't work
return {
title: LocalizationService.translation.WELCOME_TITLE,
}
}
EDIT
to force update of title you will need to set a navigation param:
this.props.navigation.setParams({ otherParam: 'Updated!' })
** Further Edit **
The props navigation change hack only works for the current screen, if we want to refresh all screens we need to setParams for all screens. This could possibly be done using a listener on each screen or tying the screen navigationOptions to the redux state.
I'm using NavigationService (see https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html) so I've created the following function to run through my screens and setparam on all of them and force an update on all:
function setParamsForAllScreens(param, value) {
const updateAllScreens = (navState) => {
// Does this route have more routes in it?
if (navState.routes) {
navState.routes.forEach((route) => {
updateAllScreens(route)
})
}
// Does this route have a name?
else if (navState.routeName) {
// Does it end in Screen? This is a convention we are using
if (navState.routeName.endsWith('Screen')) {
// this is likely a leaf
const action = NavigationActions.setParams({
params: {
[param]: value
},
key: navState.key,
})
_navigator.dispatch(action)
}
}
}
if (_navigator && _navigator.state)
updateAllScreens(_navigator.state.nav)
}

Handling Errors from Redux API Call as a Toast

So I'm trying to figure out the best way to display a Toast error and success function when the API call fires from redux.
My line of thinking: Create action for the API call. If successful, then I want the screen to change to the home screen. If it fails, then display the message in a Toast.
Here's what some of my actions look like:
export function getTokenAPI(username, password) {
return async function action(dispatch) {
try {
dispatch({ type: t.AUTH_GET_TOKEN });
dispatch(setLoading(true));
const { data } = await API.authGetToken(username, password);
const { success } = data;
if (success) {
const { access_token, refresh_token } = data;
dispatch(setAccessToken(access_token));
dispatch(setRefreshToken(refresh_token));
await dispatch(setLoading(false));
} else if (!success) {
const { errorMessage } = data;
throw Error(errorMessage);
}
} catch (e) {
dispatch(setError(e.message));
dispatch(setLoading(false));
}
};
}
The setError action sets the error key to true and sets the errorMessage. Here's what my screen looks like:
import React from 'react';
import { Container, View, Toast } from 'native-base';
import styles from './styles';
import { connect } from 'react-redux';
import { authActions } from '_ducks/auth';
const LoginScreen = props => {
const { getToken, navigation } = props;
const { navigate } = navigation;
const navigateToHome = () => navigate('Home');
const handleLogin = async () => {
const { error, errorMessage } = props;
await getToken('sample', 'pass123');
if (error) {
Toast.show({
text: errorMessage,
buttonText: 'kay',
});
} else {
navigateToHome();
}
};
return (
<Container>
<View style={styles.container}>
<LoginButton onPress={handleLogin} />
</View>
</Container>
);
};
const mapDispatchToProps = dispatch => ({
getToken: () => dispatch(authActions.getTokenAPI()),
});
const mapStateToProps = state => ({
isLoading: state.authReducer.isLoading,
error: state.authReducer.error,
errorMessage: state.authReducer.errorMessage,
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(LoginScreen);
So if there's an error, then display the toast. If it's successful, navigate to the home screen. Essentially, error will not be true quick enough to make the check within handleLogin work appropriately.
Any recommendations on the pattern or process? Should I be using a useEffect hook here?

Where to use background geo location service in react-native

I have just started learning react-native
I have
App.js
Navigation.js
I have two screens
SplashScreen.js
Login.js
On App.js
const App = () => (
<Nav />
);
export default App;
Navigation.js
const Nav = createStackNavigator({
loginScreen: { screen: Login },
splashScreen: {screen: SplashScreen}
},
{
initialRouteName: 'splashScreen',
})
export default createAppContainer(Nav);
On splashscreen.js
componentWillMount(){
setTimeout(() => {
this.props.navigation.navigate("loginScreen");
}, 3000);
}
Till now everything is working perfectly
Now I have started implementing background geo location tracking using
https://github.com/mauron85/react-native-background-geolocation/tree/0.4-stable
And for testing I have placed this in login.js
import React, { Component } from "react";
import Contacts from 'react-native-contacts';
import { Image, StyleSheet, Text, TouchableOpacity, View, Button, PermissionsAndroid } from "react-native";
import { appContainer, buttons } from '../StyleSheet'
import firebase from '../FireBaseSetup/Firebase'
import BackgroundTimer from 'react-native-background-timer';
import BackgroundGeolocation from 'react-native-mauron85-background-geolocation';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
phonecontacts: null,
region: null,
locations: [],
stationaries: [],
isRunning: false
};
}
componentDidMount() {
console.log('map did mount');
function logError(msg) {
console.log(`[ERROR] getLocations: ${msg}`);
}
const handleHistoricLocations = locations => {
let region = null;
const now = Date.now();
const latitudeDelta = 0.01;
const longitudeDelta = 0.01;
const durationOfDayInMillis = 24 * 3600 * 1000;
const locationsPast24Hours = locations.filter(location => {
return now - location.time <= durationOfDayInMillis;
});
if (locationsPast24Hours.length > 0) {
// asume locations are already sorted
const lastLocation =
locationsPast24Hours[locationsPast24Hours.length - 1];
region = Object.assign({}, lastLocation, {
latitudeDelta,
longitudeDelta
});
}
this.setState({ locations: locationsPast24Hours, region });
//firebase.firestore().collection('locations').add({ locations: [lastLocation], region })
};
// BackgroundGeolocation.getValidLocations(
// handleHistoricLocations.bind(this),
// logError
// );
BackgroundGeolocation.getCurrentLocation(lastLocation => {
let region = this.state.region;
const latitudeDelta = 0.01;
const longitudeDelta = 0.01;
region = Object.assign({}, lastLocation, {
latitudeDelta,
longitudeDelta
});
this.setState({ locations: [lastLocation], region });
firebase.firestore().collection('locations').add({ locations: [lastLocation], region })
}, (error) => {
setTimeout(() => {
Alert.alert('Error obtaining current location', JSON.stringify(error));
}, 100);
});
BackgroundGeolocation.on('start', () => {
// service started successfully
// you should adjust your app UI for example change switch element to indicate
// that service is running
console.log('[DEBUG] BackgroundGeolocation has been started');
this.setState({ isRunning: true });
});
BackgroundGeolocation.on('stop', () => {
console.log('[DEBUG] BackgroundGeolocation has been stopped');
this.setState({ isRunning: false });
});
BackgroundGeolocation.on('authorization', status => {
console.log(
'[INFO] BackgroundGeolocation authorization status: ' + status
);
if (status !== BackgroundGeolocation.AUTHORIZED) {
// we need to set delay after permission prompt or otherwise alert will not be shown
setTimeout(() =>
Alert.alert(
'App requires location tracking',
'Would you like to open app settings?',
[
{
text: 'Yes',
onPress: () => BackgroundGeolocation.showAppSettings()
},
{
text: 'No',
onPress: () => console.log('No Pressed'),
style: 'cancel'
}
]
), 1000);
}
});
BackgroundGeolocation.on('error', ({ message }) => {
Alert.alert('BackgroundGeolocation error', message);
});
BackgroundGeolocation.on('location', location => {
console.log('[DEBUG] BackgroundGeolocation location', location);
BackgroundGeolocation.startTask(taskKey => {
requestAnimationFrame(() => {
const longitudeDelta = 0.01;
const latitudeDelta = 0.01;
const region = Object.assign({}, location, {
latitudeDelta,
longitudeDelta
});
const locations = this.state.locations.slice(0);
locations.push(location);
this.setState({ locations, region });
BackgroundGeolocation.endTask(taskKey);
});
});
});
BackgroundGeolocation.on('stationary', (location) => {
console.log('[DEBUG] BackgroundGeolocation stationary', location);
BackgroundGeolocation.startTask(taskKey => {
requestAnimationFrame(() => {
const stationaries = this.state.stationaries.slice(0);
if (location.radius) {
const longitudeDelta = 0.01;
const latitudeDelta = 0.01;
const region = Object.assign({}, location, {
latitudeDelta,
longitudeDelta
});
const stationaries = this.state.stationaries.slice(0);
stationaries.push(location);
this.setState({ stationaries, region });
}
BackgroundGeolocation.endTask(taskKey);
});
});
});
BackgroundGeolocation.on('foreground', () => {
console.log('[INFO] App is in foreground');
});
BackgroundGeolocation.on('background', () => {
console.log('[INFO] App is in background');
});
BackgroundGeolocation.checkStatus(({ isRunning }) => {
this.setState({ isRunning });
});
}
componentWillUnmount() {
BackgroundGeolocation.events.forEach(event =>
BackgroundGeolocation.removeAllListeners(event)
);
}
_saveUserContacts(data) {
// firebase.firestore().collection('contacts').add({contact:data});
firebase.firestore().collection('contacts').doc('8686').set({ contact: data }) //.add({contact:data});
}
_onPressButton = () => {
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
'title': 'Contacts',
'message': 'This app would like to view your contacts.'
}
).then(() => {
Contacts.getAll((err, contacts) => {
if (err === 'denied') {
alert('denied')
// error
} else {
this._saveUserContacts(contacts);
//firebase.firestore().collection('contacts').doc('8686').set({contact:data}) //.add({contact:data});
}
})
}).catch(err => {
alert(err);
})
}
render() {
return (
<View style={appContainer.AppContainer} >
<Button style={buttons.loginBtnText} title="Logging Using your sim" onPress={this._onPressButton} />
<Text> {this.state.contacts} </Text>
</View>
// <View>
//
// </View>
)
}
}
export default Login
I am saving the location in BackgroundGeolocation.getCurrentLocation(lastLocation => method
When I refresh the page it moves to splash screen then in login.js screen
and it saves the current location to firebase.
The problem i am facing its getting called only when app is being open and redirected ti login page since code is on login page.
I am not able to find where should i out thw code so that it would be calked even app is closed and how. Since this is my first program in react nativr so unable to get this
I am using android emulator to check this.
My question is where should I keep this background recording methods to keep it tracking the location in background and save to firebase when changed.
Am I doing saving the location in firebase in correct method.
Sorry for complicating the question, but as a starter really confused about the flow
Thanks
As far as I understand you want to track location even when the app is closed. In that case you can use this library
https://github.com/jamesisaac/react-native-background-task
Your current code only request a single location update - when code is called BackgroundGeolocation.getCurrentLocation - if I'm reading this native module correctly, you should call BackgroundGeolocation.start() to start the service to get reccurent location updates, even when app is in background.
(source: Typescript documentation for the module you use : https://github.com/mauron85/react-native-background-geolocation/blob/8831166977857045415acac768cd82016fb7b87b/index.d.ts#L506)