React Navigation v5 won't reset and remove previous routes
Asked Answered
G

2

8

I have a login screen which I have placed in stack. After user logs in successfully he is redirected to home screen which is a drawer screen. One of the options of drawer screen is logout, so on click of it user should be logged out. Following is my code for logout screen. I am just showing a progress bar of logout screen in ui but in useEffect hook, I am calling the following method

navigation.navigate({index: 0, routes: [{name: LOGIN_SCREEN}]});

but I get an error saying You need to specify name or key when calling navigate with an object as the argument and I am redirected to home screen. when I restart my app completely then only it moves to login screen. I am passing the right value for name key.

My Navigation stack looks something as follows

 <Stack.Navigator>

      <Stack.Screen
        name={LOGIN_SCREEN}
        component={LoginScreen}
        options={{headerShown: false}}
      />
     <Stack.Screen
        name={HOME_STACK_SCREEN}
        component={DrawerStack}
        options={{headerShown: false}}
      />...

My drawer component as follows

<Drawer.Navigator
      drawerStyle={{backgroundColor: BLUE_COLOR_1}}
      drawerContentOptions={{labelStyle: {color: '#FFF'}}}>
      <Drawer.Screen
        name={HOME_SCREEN}
        component={Home}
        options={{
         ...
        }}
      />
     <Drawer.Screen
        name={LOGOUT_SCREEN}
        component={Logout}
        options={{
         ...
        }}
      />
Gargantua answered 29/2, 2020 at 14:57 Comment(1)
how are you navigating from Login Stack to Drawer, with reset?Waldack
O
16

If you want to reset then you need to use reset, not navigate:

navigation.reset({
  routes: [{ name: LOGIN_SCREEN }]
});
Osmium answered 29/2, 2020 at 21:18 Comment(4)
Thanks for the answer but I get a dialog saying Invariant violation. Maximum depth exceeded after replacing navigate with resetGargantua
this might be related to this github.com/react-navigation/hooks/issues/35Gargantua
LOGIN_SCREEN should be in quotesShed
depends on if it's a variable or a string, it's a variable in OPOsmium
H
16

In react-navigation v5. You can reset navigation like this

import { CommonActions } from "@react-navigation/native";

this.props.navigation.dispatch(
     CommonActions.reset({
        index: 0,
        routes: [{ name: "LOGIN_SCREEN" }],
    })
);
Hong answered 24/4, 2020 at 15:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.