Anony dev
Anony dev

Reputation: 13

BackHandler is getting called from all pages

I am new to React Native. I have written following function for handling back button press:

useEffect(() => {
  const backAction = () => {
    Alert.alert('Hold on!', 'Are you sure you want to Logout?', [
      {
        text: 'Cancel',
        onPress: () => null,
        style: 'cancel',
      },
      { text: 'YES', onPress: logout },
    ]);
    return true;
  };

  const backHandler = BackHandler.addEventListener(
    'hardwareBackPress',
    backAction
  );

  return () => backHandler.remove();
}, []);

This is my logout function:

async function logout() {
  setLoginState(true);
  const user1 = await Auth.currentAuthenticatedUser();
  const token1 = user1.signInUserSession.idToken.jwtToken;
  console.log('toekn 1  ' + token1);
  try {
    await Auth.signOut();
    setLoginState(false);
  } catch (error) {
    console.log('error signing out: ', error);
    setLoginState(false);
  }
  {
    loginState ? <Loader /> : console.log('None');
  }

  props.navigation.navigate('Login');
}

The problem is that when I am pressing the back button on some other page, even then the backAction function is getting called. Kindly suggest.

Upvotes: 1

Views: 599

Answers (2)

Hamid khan
Hamid khan

Reputation: 57

I think you forgot the removing of Listener in screens; remove it in each screen then try again. See the code below:

  return () =>
     remove here
   })
 

Upvotes: 0

Kartikey
Kartikey

Reputation: 4992

To handle Back press, I would suggest you to follow these steps:-

Create a Folder Called hooks where your App.js is located.

Inside hooks folder create a file called useBackHandler.js

Your useBackHandler.js should look like this

import { useEffect } from "react";
import { BackHandler } from "react-native";

export function useBackHandler(handler) {
  useEffect(() => {
    BackHandler.addEventListener("hardwareBackPress", handler);

    return () => BackHandler.removeEventListener("hardwareBackPress", handler);
  }, [handler]);
}

Now, to use this handler what you need to do is shown below.

useBackHandler(() => {
  if (someCondition) {
    // Handle Backpress here
    return true;
  }
  // Let Backpress behave as default
  return false;
});

So in your case, you should then use it like this

useBackHandler(() => {
  Alert.alert('Hold on!', 'Are you sure you want to Logout?', [
    {
      text: 'Cancel',
      onPress: () => null,
      style: 'cancel',
    },
    { text: 'YES', onPress: logout },
  ]);
  return true;
});

Upvotes: 1

Related Questions