0

I am trying to a make a trigger whenever the user presses the back button from their phone to call a function (where the function will go back to the previous screen with the necessary parameters that I need for the app to work correctly), however either it is ignoring the function, or it's not passing it at all, and I can't figure out why.

I looked at these resources and they didn't help me in this particular case:

React Native - Device back button handling

https://reactnative.dev/docs/backhandler

This is part of the code I used, going back from the chat screen to the user's profile screen

import { BackHandler } from "react-native";

function handleBackButtonClick() {
  props.navigation.navigate("MenuScreen", {
      screen: "userProfileScreen", 
      params: {
          accountId: managerId,
          origin: "chatScreen"
      }
  });
  return true;
}

useEffect(() => {
  BackHandler.addEventListener("hardwareBackPress", handleBackButtonClick);
  return () => {
    BackHandler.removeEventListener("hardwareBackPress", handleBackButtonClick);
  };
}, []);

When I call the function from an onPress, it works as intended

        <TouchableOpacity style={{ height: 48, width: 48, justifyContent: "center" }}
            onPress={() => handleBackButtonClick()}>
            <Text>Clicking here works as intended</Text>
        </TouchableOpacity>

Am I doing something fundamentally wrong with the handleBackButtonClick? How do I make it work?

Edit: For more information, it is built upon multiple stack navigators in the menu navigator, which you can see here:

const Stack = createNativeStackNavigator();

function MenuNavigator({ route }) {
    return (
        <Stack.Navigator screenOptions={() => ({ headerShown: false })}>
            <Stack.Screen name="inDevelopmentScreen" component={InDevelopmentScreen} />
            <Stack.Screen name="profileScreen" component={ProfileScreen} />
            <Stack.Screen name="myScreen" component={MyScreen} />
            <Stack.Screen name="userProfileScreen" component={UserProfileScreen}
                listeners={({ navigation }) => ({
                    blur: () => {
                        navigation.setParams({ accountId: undefined })
                    }
                })} />
            <Stack.Screen name="otherScreen" component={OtherScreen} />
            <Stack.Screen name="chatScreen" component={ChatScreen} />
          /* Ect... */
        </Stack.Navigator>
    );
}
Joeygr
  • 57
  • 5
  • I know nothing about react-native, but making users navigate on the back button click seems like some kind of violation. – Konrad Sep 05 '22 at 16:11
  • You might be right on that instinct @Konrad I would prefer to have a way of going back dynamically without manually telling it where the user should navigate to. It works to go back normally, however since the screen before itself is no longer at work, the variables and constants disappear and I can no longer use them. So my solution was to just pass a parameter to know which profile it should show using the user's ID, not sure if that's a bad practice for mobile coding in general though – Joeygr Sep 05 '22 at 16:16

1 Answers1

0

Your code looks fine, so I think maybe the function is not being executed because of how the hooks work in react native. Here is a code I did in a project that is working so maybe you can try to use the useEffect the same way (function in array) and a useCallback in your handleBackButtonFunction.

  const handleBackButtonClick = useCallback(() => {
    if (title) {
      navigation.dispatch(StackActions.pop(2));
    } else {
      navigation.goBack();
    }
    return true;
  }, [navigation, title]);

  useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress', handleBackButtonClick);

    return () => {
      BackHandler.removeEventListener(
        'hardwareBackPress',
        handleBackButtonClick
      );
    };
  }, [handleBackButtonClick]);
Oleg Barabanov
  • 2,468
  • 2
  • 8
  • 17