trying to show alert when modal is closed

37 Views Asked by At

I am building an app using React Native. Specifically, I have modals using React Navigation, where you set the presentation prop to "modal" for a Stack.Screen. I have a modal where users can type in text and then save it. I want it so that if the user tries to swipe down on the modal, an alert will pop up asking them if they want to save the review (the only way to save the review is by pressing a button on the modal, which will automatically close the modal).

I tried to do this:

  React.useEffect(
    () =>
      navigation.addListener('beforeRemove', (e) => {
        const action = e.data.action;
        if (!hasUnsavedChanges) {
          return;
        }

        e.preventDefault();

        Alert.alert(
          'Discard review?',
          'You have an unsaved review.',
          [
            { text: "Don't leave", style: 'cancel', onPress: () => {} },
            {
              text: 'Discard',
              style: 'destructive',
              onPress: () => navigation.dispatch(action),
            },
          ]
        );
      }),
    [hasUnsavedChanges, navigation]
  );

The issue is that it doesn't work with swiping. When I swipe, it closes the modal and THEN shows me the alert, along with an error "the screen "review" was removed natively but didn't get removed from a JS state. this can happen if the action was prevented in a 'beforeRemove' listener, which is not fully supported in native-stack." I am using createStackNavigator, not the native stack, so I'm not sure what that error is.

I have a "save" button that automatically closes the modal by navigating back to the navbar screen -- when I click it, the alert does show up. It's essentially reversed: I want the alert to appear when I swipe down, and not to appear when I click the save button. How can I fix this?

0

There are 0 best solutions below