Skip to content

Commit

Permalink
fix: show error when beforeRemove is used to prevent action in naive …
Browse files Browse the repository at this point in the history
…stack
  • Loading branch information
satya164 committed Nov 27, 2022
1 parent 9687c1a commit 61505bc
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
10 changes: 3 additions & 7 deletions example/src/Screens/PreventRemove.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
CommonActions,
NavigationAction,
ParamListBase,
useTheme,
} from '@react-navigation/native';
Expand Down Expand Up @@ -69,10 +68,7 @@ const InputScreen = ({
React.useEffect(
() =>
navigation.addListener('beforeRemove', (e) => {
const action: NavigationAction & { payload?: { confirmed?: boolean } } =
e.data.action;

if (!hasUnsavedChanges || action.payload?.confirmed) {
if (!hasUnsavedChanges) {
return;
}

Expand All @@ -84,7 +80,7 @@ const InputScreen = ({
);

if (discard) {
navigation.dispatch(action);
navigation.dispatch(e.data.action);
}
} else {
Alert.alert(
Expand All @@ -95,7 +91,7 @@ const InputScreen = ({
{
text: 'Discard',
style: 'destructive',
onPress: () => navigation.dispatch(action),
onPress: () => navigation.dispatch(e.data.action),
},
]
);
Expand Down
20 changes: 20 additions & 0 deletions packages/native-stack/src/views/NativeStackView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,24 @@ type Props = {
};

function NativeStackViewInner({ state, navigation, descriptors }: Props) {
const [nextDismissedKey, setNextDismissedKey] =
React.useState<string | null>(null);

const dismissedRouteName = nextDismissedKey
? state.routes.find((route) => route.key === nextDismissedKey)?.name
: null;

React.useEffect(() => {
if (dismissedRouteName) {
const message =
`The screen '${dismissedRouteName}' was removed natively but didn't get removed from JS state. ` +
`This can happen if the action was prevented in a 'beforeRemove' listener, which is not fully supported in native-stack.\n\n` +
`Consider using 'gestureEnabled: false' to prevent back gesture and use a custom back button with 'headerLeft' option to override the native behavior.`;

console.error(message);
}
}, [dismissedRouteName]);

return (
<ScreenStack style={styles.container}>
{state.routes.map((route, index) => {
Expand Down Expand Up @@ -173,6 +191,8 @@ function NativeStackViewInner({ state, navigation, descriptors }: Props) {
source: route.key,
target: state.key,
});

setNextDismissedKey(route.key);
}}
>
<HeaderConfig
Expand Down

0 comments on commit 61505bc

Please sign in to comment.