Canceling all async functions when navigation changes in react native - javascript

When this component loads, the startSync function starts. However, I also have an exit function that navigates to a login screen if pressed during any of this.
What happens though is, if I press the exit button, it brings me back to the login page. However, the async function is still running so when it finishes it will then navigate me to the Identification screen.
I was wondering if there is a way to cancel all Async function's so that nothing is running in the background after the exit button is pushed.
import React, { Component } from 'react';
import { ActivityIndicator, AsyncStorage, Button, StatusBar, Text, StyleSheet, View, } from 'react-native';
import * as pouchDB_helper from '../utils/pouchdb';
type Props = {};
export default class SyncScreen extends Component<Props> {
startSync = async () => {
pouchDB_helper.sync().then((response) => {
AsyncStorage.setItem('initial_sync', 'true');
//navigate to the identification page
this.props.navigation.navigate('Identification');
}, (error) => { Alert.alert("Error", "Syncing failed. Please try again."); });
}
exit = async () => {
await AsyncStorage.clear();
this.props.navigation.navigate('Login');
}
componentDidMount() {
this.startSync();
}
static navigationOptions = {
title: 'Syncing Settings',
};
render() {
return (
<View style={styles.container}>
<Text style={styles.footerText} onPress={this.exit}>Exit</Text>
</View>
);
}
}

Related

TypeError _this2.getWifiList().bind is not a function. React Native componentDidMount

I'm trying to get my app to refresh a select components list of options. The list will show a selection of wifi hotspots and I want the app to scan for them every 5 seconds, so I followed this guide: https://blog.stvmlbrn.com/2019/02/20/automatically-refreshing-data-in-react.html
But when I run the app, I get this error:
Error
Possible Unhandled Promise Rejection (id: 0):
TypeError: _this2.getWifiList().bind is not a function. (In '_this2.getWifiList().bind((0, _assertThisInitialized2.default)(_this2))', '_this2.getWifiList().bind' is undefined)
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:187369:75
tryCallOne#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27870:16
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27971:27
_callTimer#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:31410:17
_callImmediatesPass#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:31449:17
callImmediates#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:31666:33
__callImmediates#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3610:35
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3396:34
__guard#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3593:15
flushedQueue#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3395:21
flushedQueue#[native code]
invokeCallbackAndReturnFlushedQueue#[native code]
This error comes up 10 times in a second. I tried removing the bind but I get the same error.
MainScreen.js
import React, {useState} from 'react';
import { StyleSheet, PermissionsAndroid, Linking, View, TouchableOpacity } from 'react-native';
import { IndexPath, Layout, Text, Button, Select, SelectItem } from '#ui-kitten/components';
import { Icon } from 'react-native-eva-icons';
import {styles} from '../styles'
import WifiManager from "react-native-wifi-reborn";
class LocationSelector extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedIndex : (new IndexPath(0)),
wifiList: null,
intervalID: null,
}
}
componentDidMount() {
this.getWifiList();
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
getWifiList = async () => {
WifiManager.setEnabled(true);
await WifiManager.reScanAndLoadWifiList()
.then((data) => {
this.state.wifiList = data
this.intervalID = setTimeout( async () => {await this.getWifiList().bind(this)}, 5000);
});
}
renderOption = (title) => (
<SelectItem title={title}/>
)
render() {
console.log(this.state.selectedIndex);
const data = [
'Venue1',
'Venue2',
'Venue3',
];
const displayValue = data[this.state.selectedIndex.row];
return(
<Select
style={styles.select}
size="large"
placeholder='Default'
value={displayValue}
disabled={this.props.disabled}
accessoryLeft={PinIcon}
selectedIndex={this.state.selectedIndex}
onSelect={(index) => {(this.state.selectedIndex = index); this.forceUpdate()}}>
{data.map(this.renderOption)}
</Select>
);
}
}
class MainScreen extends React.Component {
constructor(props) {
super(props);
this.navigation = props.navigation
this.state = {
isCheckedIn: false,
}
}
render() {
return (
<Layout style={styles.container}>
<LocationSelector />
</Layout>
);
}
}
export default MainScreen;
The issue is in the way you are calling .bind():
this.getWifiList().bind(this)
Note that .bind() is a method of the Function prototype, therefore, is available only when called on a function reference.
In this case, you are calling .bind() on this.getWifiList(), which is the return value of getWifiList, not the functon itself.
To fix the error you are getting, you just need to call it on the function:
this.getWifiList.bind(this)

How to get async data without reloading whole app

I am trying when the user clicks on bottomTabNavigator the component screen will reload. I mean in my first component screen "AnotherA.js", I am using textinput which store user entered data in async storage and in another component "AnotherB.js" I am using get() of async storage to show my stored data on the screen. I am able to see the stored data the first time while reloading the whole app.
I am trying to get data without reloading, the whole app, by navigating with bottomTabNavigator it displays immediately.
//App.js
import React, { Component } from "react";
import { createAppContainer } from 'react-navigation';
import { createMaterialBottomTabNavigator } from 'react-navigation-material-bottom-tabs';
import { TabNavigator } from 'react-navigation';
import AnotherA from './AnotherA';
import AnotherB from './AnotherB';
const AppNavigator = createMaterialBottomTabNavigator(
{
AnotherA: { screen: AnotherA },
AnotherB: { screen: AnotherB }
},
{
initialRouteName: 'AnotherA',
activeColor: '#f0edf6',
inactiveColor: '#3e2465',
barStyle: { backgroundColor: '#694fad' },
pressColor: 'pink',
},
{
//tabBarComponent: createMaterialBottomTabNavigator /* or TabBarTop */,
tabBarPosition: 'bottom',
defaultnavigationOptions: ({ navigation }) => ({
tabBarOnPress: (scene, jumpToIndex) => {
console.log('onPress:', scene.route);
jumpToIndex(scene.index);
},
}),
}
);
const AppContainer = createAppContainer(AppNavigator);
export default AppContainer;
//AnotherA.js
import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from './styles';
export default class AnotherA extends Component {
constructor(props) {
super(props);
this.state = {
myKey: '',
text1: '',
}
}
async getKey() {
try {
//const value = await AsyncStorage.getItem('#MySuperStore:key');
const key = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: key,
});
} catch (error) {
console.log("Error retrieving data" + error);
}
}
async saveKey(text1) {
try {
await AsyncStorage.setItem('#MySuperStore:key', text1);
} catch (error) {
console.log("Error saving data" + error);
}
}
async resetKey() {
try {
await AsyncStorage.removeItem('#MySuperStore:key');
const value = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: value,
});
} catch (error) {
console.log("Error resetting data" + error);
}
}
componentDidMount() {
this.getKey();
}
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Enter Data"
value={this.state.myKey}
onChangeText={(value) => this.setState({ text1: value })}
multiline={true}
/>
<Button
onPress={() => this.saveKey(this.state.text1)}
title="Save"
/>
<Button
//style={styles.formButton}
onPress={this.resetKey.bind(this)}
title="Reset"
color="#f44336"
accessibilityLabel="Reset"
/>
</View>
)
}
}
//AnotherB.js
import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from './styles';
export default class AnotherB extends Component {
constructor(props) {
super(props);
this.state = {
myKey: '',
text1: '',
}
}
async getKey() {
try {
//const value = await AsyncStorage.getItem('#MySuperStore:key');
const key = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: key,
});
} catch (error) {
console.log("Error retrieving data" + error);
}
}
componentDidMount() {
this.getKey();
}
render() {
//const { navigate } = this.props.navigation;
//const { newValue, height } = this.state;
return (
<View style={styles.container}>
<Text>{this.state.myKey}</Text>
</View>
)
}
}
Please suggest, I am new to React-Native.
The issue is that you are retrieving the value from AsyncStorage when the component mounts. Unfortunately that isn't going to load the value on the screen when you switch tabs. What you need to do is subscribe to updates to navigation lifecycle.
It is fairly straight forward to do. There are four lifecycle events that you can subscribe to. You can choose which of them that you want to subscribe to.
willFocus - the screen will focus
didFocus - the screen focused (if there was a transition, the transition completed)
willBlur - the screen will be unfocused
didBlur - the screen unfocused (if there was a transition, the transition completed)
You subscribe to the events when the component mounts and then unsubscribe from them when it unmounts. So when the event you have subscribed to happens, it will call the function that you have put into the subscriber's callback.
So you can do something like this in you AnotherB.js:
componentDidMount() {
// subscribe to the event that we want, in this case 'willFocus'
// when the screen is about to focus it will call this.getKey
this.willFocusSubscription = this.props.navigation.addListener('willFocus', this.getKey);
}
componentWillUnmount() {
// unsubscribe to the event
this.willFocusSubscription.remove();
}
getKey = async () => { // update this to an arrow function so that we can still access this, otherwise we'll get an error trying to setState.
try {
const key = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: key,
});
} catch (error) {
console.log("Error retrieving data" + error);
}
}
Here is a quick snack that I created showing it working, https://snack.expo.io/#andypandy/navigation-life-cycle-with-asyncstorage
You can try to add then after getItem
AsyncStorage.getItem("#MySuperStore:key").then((value) => {
this.setState({
myKey: value,
});
})
.then(res => {
//do something else
});

How can I navigate once when I found a JWT?

I am just getting stuck into react-native and need some help navigating to a protected screen when a token is found. Where should I look for a token on app load? And how can I navigate the user once without calling navigate multiple times? The problem I have is I am checking for a token on component mount, which is nested inside a stack. If I navigate to another part of the stack, the function is called again and I am unable to navigate. I can retrieve the token outside of the stack, but then I am having trouble navigating, as I need to pass props.navigate within a screen component. What is the recommended approach to finding a token, and making a navigation?
App.js
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import store from './store';
import RootContainer from './screens/RootContainer';
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<RootContainer />
</Provider>
);
}
}
RootContainer.js
...
render() {
const MainNavigator = createBottomTabNavigator({
welcome: { screen: WelcomeScreen },
auth: { screen: AuthScreen },
main: {
screen: createBottomTabNavigator({
map: { screen: MapScreen },
deck: { screen: DeckScreen },
review: {
screen: createStackNavigator({
review: { screen: ReviewScreen },
settings: { screen: SettingsScreen }
})
}
})
}
// Route Configuration for Initial Tab Navigator
}, {
// do not instantly render all screens
lazy: true,
navigationOptions: {
tabBarVisible: false
}
});
return (
<View style={styles.container}>
<MainNavigator />
</View>
);
}
}
WelcomeScreen.js
...
componentDidMount(){
this.props.checkForToken(); // async method
}
// Async Action
export const checkForToken = () => async dispatch => {
console.log("action - does token exist ?");
let t = await AsyncStorage.getItem("jwt");
if (t) {
console.log("action - token exists");
// Dispatch an action, login success
dispatch({ type: LOGIN_SUCCESS, payload: t });
} else {
return null;
}
}
// WelcomeScreen.js continued
componentWillRecieveProps(nextProps){
this.authComplete(nextProps);
}
authComplete(props){
if(props.token){
props.navigation.navigate('map'); // called again and again when I try to navigate from within the Bottom Tab Bar Component
}
}
render(){
if(this.props.appLoading){ // default True
return ( <ActivityIndicator />);
}
return ( <Text>WelcomeScreen</Text> );
}
const mapStateToProps = state => {
return {
token: state.auth.token,
appLoading: state.auth.appLoading // default True
};
};
export default connect(mapStateToProps, actions)(WelcomeScreen);
I would suggest, not to store navigation state in redux.
Just navigate when you found a token or the user logged in.
If you still want to use redux or simply want to react on props changes, then the way is to use some Redirect Component, and render it only when the token changed from nothing to something. You could read about such implementation from react-router here. I think there is no such implementation for React Navigation.
When you are using React Navigation, then I would suggest to look into the docs, because I think it solves the problem you have.
https://reactnavigation.org/docs/en/auth-flow.html

Alert prompt to function not working in react native

I have a button on my page that prompts an alert. If that user selects Yes, I then want the exit() function to run. However, the way it is coded now, for some reason nothing happens.
Does anyone know what I am doing wrong?
import React, { Component } from 'react';
import { ActivityIndicator, AsyncStorage, Button, StatusBar, Text, StyleSheet, View, TextInput, Alert } from 'react-native';
type Props = {};
export default class IDScreen extends Component<Props> {
static navigationOptions = {
title: 'Identification',
};
exit = async () => {
alert("I should see this but I don't");
await AsyncStorage.clear();
this.props.navigation.navigate('Login');
}
promptExit() {
Alert.alert("Are you sure?", "You can't be serious.", [
{text: 'Yes, Sign out', onPress: async () => this.exit },
{text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
],
{ cancelable: true });
}
render() {
return (
<View style={styles.container}>
<Text style={styles.footerText} onPress={this.promptExit}>Sign Out</Text>
</View>
);
}
}
Try This method it Will Work
Invoke Alert.alert() function from Button, instead of calling Inside of another function, It will work, just see the code snippet.
And exit is an arrow function invoke like this "this.exit()" instead of this.exit.
import React, { Component } from 'react';
import {
ActivityIndicator,
AsyncStorage,
Button,
StatusBar,
Text,
StyleSheet,
View,
TextInput,
Alert } from 'react-native';
type Props = {};
export default class IDScreen extends Component<Props> {
static navigationOptions = {
title: 'Identification',
};
exit = async () => {
alert("I should see this but I don't");
await AsyncStorage.clear();
this.props.navigation.navigate('Login');
}
render() {
return (
<View style={styles.container}>
<Text style={styles.footerText}
onPress={
() => Alert.alert(
"Are you sure?", "You can't be serious.",
[
{text: 'Yes, Sign out', onPress: async () => this.exit() },
{text: 'Cancel', onPress: () => console.log('Cancel Pressed'),
style: 'cancel'},
],
{ cancelable: true });
}
}>Sign Out</Text>
</View>
);
}
}
You need to modify promptExit() to an arrow function promptExit = () =>.
Arrow functions are used, not to redefine the value of this , inside their body, it simply means same thing within the function body as it does outside of it.
Since the function is called without its reference to a particular object, like yourObj.yourMethod(), therefore you either need to bind it in the class constructor / render or use arrow function.
Without it , it would lose it's context and will always be undefined or a global object.
Similarly, you can also read
When not to use arrow functions

Async helper functions with AsyncStorage in React Native

What I am trying to do is alert the company_id that is in local storage.
import React, { Component } from 'react';
import { ActivityIndicator, AsyncStorage, Button, StatusBar, Text, StyleSheet, View, } from 'react-native';
import * as pouchDB_helper from '../utils/pouchdb';
type Props = {};
export default class HomeScreen extends Component<Props> {
render() {
AsyncStorage.getItem('company_id', (err, result) => {
alert(result);
});
return (
<View style={styles.container}>
<Button title="Hi" onPress={this.doSomething} />
</View>
);
}
}
The following code works but I want to be able to do it from inside a helper function. If you see at the top, I have import * as pouchDB_helper from '../utils/pouchdb';
In there I have the following:
import React from 'react';
import { AsyncStorage } from 'react-native';
import PouchDB from 'pouchdb-react-native'
export async function pouchDB_config() {
return AsyncStorage.getItem('company_id', (err, result) => {
return result;
});
}
Instead of AsyncStorage.getItem() code, if I do alert(pouchDB_helper.pouchDB_config()) I get an object with the following: {"_40":0,"_65":0,"_55"_null,"72":null}
I know I'm obviously not doing something right with the whole asynchronous nature of it all so if anyone has any guidance I would greatly appreciate it. I'm still not up to par with how to work with async functions in react native.
This is beacause when you call the function pouchDB_helper.pouchDB_config() it returns a promise.
There are different ways to use this to your advantage.
In your util/pouchdb change the function as following:
export async function pouchDB_config() {
return await AsyncStorage.getItem('company_id');
}
Now you can call this function as follows:
pouchDB_config().then((company_id) => {
console.log(company_id);
});
Or you can call it anywhere else within an async function:
const otherAsyncFunction = async () => {
const company_id = await pouchDB_config();
console.log(company_id);
}

Categories