React Navigation 'beforeRemove' event is not getting fired in React Native

Viewed 5399

I am trying to prevent user from going back by Android back button or gesture while a video is being recorded in React Native. As per documentation of React Navigation, it should be handled with the beforeRemove event listener. But the event is never being fired when going back.

I tried with blur, it was getting fired though, but since this event doesn't have a preventDefault() method, it's not usable in this scenario.

React Navigation - v5.x

React Native - 0.63.2

Here's the sample code for the screen I am trying to achieve

const VideoCapturePage = ({navigation}) => {
  const [isRecording, setIsRecording] = useState(false);

  useEffect(() => {
    navigation.addListener('beforeRemove', (e) => {
      if (!isRecording) {
        return;
      }

      e.preventDefault();

      Alert.alert(
        'Unsaved changes',
        'There are unsaved changes. Please chose what you want.',
        [
          {
            text: 'Go back',
            onPress: () => {
              navigation.dispatch(e.data.action);
            },
          },
          {
            text: 'Cancel',
            onPress: () => {
              console.log('cancelled');
            },
          },
          {
            text: 'Continue to Edit',
            onPress: () => {
              console.log('continue');
            },
          },
        ],
        {
          cancelable: false,
        },
      );
    });
  }, [navigation, isRecording]);

  return (
    <View style={styles.container}>
      <VideoCamera
        isRecording={isRecording}
        setIsRecording={setIsRecording}
      />
    </View>
  );
};
1 Answers

Acording to document you dont use in tab/ drawer navigation. You use only Modal and other areas. "Note that this event is only triggered whenever a screen is being removed. For example:

The user pressed back button on a screen in a stack The user performed a swipe back gesture Some action such as pop or reset was dispatched which removes the screen from the state This event is not triggered when a screen is being unfocused, but not removed. For example:

The user pushed a new screen on top of the screen with the listener in a stack The user navigated from one tab/drawer screen to another tab/drawer screen"

Related