Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all articles
Browse latest Browse all 30347

React Native BackHandler not removing event Listener

$
0
0

I am using React Navigation and I need some custom functionality when back button is pressed. Here is my code:

class AddEditIngredient extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editStarted: false
    };
    this.goBack = () => {
      if (this.state.editStarted === true) {
        Alert.alert(
          "Ingredient Not Saved",
          "Do you want to navigate away without saving ingredient?",
          [
            { text: "Cancel", onPress: () => null, style: "cancel" },
            { text: "Yes", onPress: () => this.props.navigation.goBack() }
          ],
          { cancelable: true }
        );
      } else {
        this.props.navigation.goBack();
      }
    };
}

componentWillMount() {
    BackHandler.addEventListener("hardwareBackPress", this.goBack);
}

componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.goBack);
}

My goBack function works fine for back button on screen, however when I try to press the physical back button it pops out all the screens and minimizes the application. From what I have gathered by reading previous posts on the issue, removeEventListener is not referring to the same function as addEventListener. So I tried this:

constructor(props) {
    super(props);
    this.state = {
      editStarted: false
    };
    this.goBack = this.goBack.bind(this);
}
goBack = () => {
      if (this.state.editStarted === true) {
        Alert.alert(
          "Ingredient Not Saved",
          "Do you want to navigate away without saving ingredient?",
          [
            { text: "Cancel", onPress: () => null, style: "cancel" },
            { text: "Yes", onPress: () => this.props.navigation.goBack() }
          ],
          { cancelable: true }
        );
      } else {
        this.props.navigation.goBack();
      }
    };

But it didn't work. Can anyone point out my mistake?

Thanks


Viewing all articles
Browse latest Browse all 30347

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>