I have registered an event for handling the hardware back button press in the Home Screen. Whenever I click the back button when I am in the home screen, it will ask me for the exit confirmation alert box. I want this behaviour to happen only in the Home screen, not in any other screen. When I am in some other screen, let's say Setting Screen and I click the back button, it still shows me the exit confirmation alert box. It seems like the event I registered on the Home Screen has not been removed.
const backAction = () => {
Alert.alert('Close the KhataBook app?', 'Are you sure you want to exit?', [
{
text: 'Cancel',
onPress: () => null,
style: 'cancel',
},
{text: 'YES', onPress: () => BackHandler.exitApp()},
]);
return true;
};
useEffect(() => {
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
backAction,
);
return () => backHandler.remove();
}, []);
CodePudding user response:
Try to remove listener like in docs , with removeEventListener method
useEffect(() => {
BackHandler.addEventListener("hardwareBackPress", backAction);
return () =>
BackHandler.removeEventListener("hardwareBackPress", backAction);
}, []);
CodePudding user response:
If you are using react navigation you can achieve that by doing the following:
useFocusEffect(() => {
const backHandler = BackHandler.addEventListener(
'hardwareBackPress', ()=>{ navigation.goBack(); return true; });
return () => {
backHandler.remove();
};
});