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>
);
}
}
You can use the cancelable option that's passed to Alert. alert(title, message, buttons, {cancelable: true} . Moreover, you can pass a function onDismiss , so that you know that the user didn't choose anything! Hope this helped!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With