How to reset a Stack Navigator on blur? (React Native, React Navigation)

Viewed 1040

So I have the following navigation structure:

NavigationContainer
--Tab.Navigator
----Tab.Screen (Home)
------Stack.Navigator
--------Stack.Screen (Overview)
--------Stack.Screen (Goals)
--------Stack.Screen (Economy)
----Tab.Screen (Stats)
------Stack.Navigator
--------Stack.Screen (Overview)
--------Stack.Screen (Economy Page)
--------Stack.Screen (Consumption Page)
----Tab.Screen (Challenges)
----Tab.Screen (Data)

Now the issue is that I want all of the stack navigators to reset to the default overview page when the tabs are changed. Meaning that for example if you are on the homescreen overview, enter goals stackscreen, change the tab to stats, and then go back to the home tab, you are back on the overview, but right now it would still be on the goals screen.

I have tried using the CommonActions method from react navigation like this:

navigation.addListener('blur', () => {
    console.log('Home screen changed');
    navigation.dispatch(
        CommonActions.reset({
          index: 1,
          routes: [
            { name: HomeScreens.Start },
          ],
        }),
    );
  });

But the issue is that the navigation element refers to the parent Navigator. Meaning that the reset also happens if you within each Stack Navigator, something I do not want.

Right now my homescreen looks like this:

export function HomeScreen({ navigation }:any) {
  return (
    <NavigationContainer independent = {true} >
      <Stack.Navigator initialRouteName={HomeScreens.Start} headerMode = "none">
        <Stack.Screen name = {HomeScreens.Start} component={StartPage} />
        <Stack.Screen name= {HomeScreens.Economy} component={EconomyPage} />
        <Stack.Screen name= {HomeScreens.Goal} component={GoalPageFunc} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Is it possible to do something here to reset the stacknavigator when the tabs are changed, but not when navigating within the stack navigator?

1 Answers

You can try this solution that was posted in an issue on github:

Add the blur listener and set unmountOnBlur: true on the Tab.Screen you want to reset. In your example it would be the Tab.Screen (Home)

    <Tab.Navigator>
      <Tab.Screen name="FirstScreen" component={FirstScreen} />
      <Tab.Screen
        name="SecondScreen"
        component={SecondScreenStack}
        options={{unmountOnBlur: true}}
        listeners={({navigation}) => ({blur: () => navigation.setParams({screen: undefined})})}
      />
      <Tab.Screen name="ThirdScreen" component={ThirdScreen} />
    </Tab.Navigator>

Related