1

i have bottom tab stack....in each stack there are either single screen or nested stack navigator.

Problem:

first tab - Home screen second tab - MyDetailsStack(createStackNavigator) - detailScreen1 (initialRoute) - detailScreen2

Goal: when user visits detail detailScreen2.... then goes back go homescreen and clicks back second tab....i need to reset the second tab to show initial route it is pointing which is detailScreen1. At this moment what ever screen i left (that is detailScreen2) is shown.

Please check the expo for the problem.

https://snack.expo.dev/@rosnk/nested-route-reset-on-tabchange

Currently tried solution:

  1. tried adding following code:
<Tab.Screen
        name="MyDetailsTabStack"
        component={MyDetailsStack}
        options={{
          title: 'My Details',
          tabBarLabel: 'My Details',
        }}
        listeners={({ navigation, route }) => ({
          tabPress: (e) => {
            navigation.dispatch(
              CommonActions.reset({
                index: 1,
                routes: [
                  { name: 'DetailScreen1' },
                  {
                    name: 'DetailScreen2',
                  },
                ],
              })
            );
          },
        })}
      />

tried solution reference to this stack suggestion: How to reset a Stack in a different Tab using React Navigation 5.x

rosnk
  • 1,068
  • 1
  • 14
  • 36

1 Answers1

1

I was also having this problem. I want to reset the navigation stack back to the first index when the user leaves the tab. I followed the reference in your link and from that, created my solution to the problem.

Using the useFocusEffect() described here, and after reading about the Navigation Lifecycle here, below is my solution that works for me.

const { reset } = useNavigation();
useFocusEffect(
  useCallback(() => {
    // If you want to do something when screen is focused
    return () => {
      // This is called when the screen is not focused
      // i.e. switched to a different tab or the hardware back button is pressed (Android)
      reset({ index: 0, routes: [{ name: "detailScreen1" }] });
    };
  }, []),
);

Place this inside your detailScreen2 and it should reset back that stack navigators state whenever the user leaves the screen

Echo
  • 521
  • 5
  • 16