0

My application flow as below:-

App.js
│
└── AppSwitchNavigator
            └── MainSplash: { screen: SplashScreen }
            └── Auth: { screen: AuthStack } // createStackNavigator
            │       └── SignIn: { screen: MainSignIn }
            │       └── Register: { screen: MainRegister }
            │
            └── Dashboard: { screen: TabHelper } // createBottomTabNavigator
                    └── Home: { screen: HomeStack }
                    └── Favourite: { screen: FavouriteScreen }
                    └── Cart: { screen: CartStack }
                    └── Profile: { screen: ProfileStack }
                            └── MainProfile: { screen: ProfileScreen }
                            └── ChangePassword: { screen: PasswordScreen }
                            └── TrackOrder: { screen: TrackStack }

On ProfileScreen I have placed header with logout button as below. enter image description here

<Header >
  <Left style={{ flex: null }}>
  </Left>
  <Body style={{ flex: 3 }}>
    <Title style={{ marginLeft: 10, }}>User Profile</Title>
  </Body>
  <Right style={{ flex: null }}>
    <Button hasText transparent onPress={() => Alert.alert(
      'Log out',
      'Do you want to logout?',
      [
        { text: 'Cancel', onPress: () => { return null } },
        { text: 'Confirm', onPress: () => { this.Func_LogoutUser() } },
      ],
      { cancelable: false }
    )}>
      <Text>Logout</Text>
    </Button>
  </Right>
</Header>

I cannot logout to Auth switch. I have try:-

this.props.navigation.navigate('Auth'); => Nothing happen

I also try this approach from here

const subAction = NavigationActions.navigate({ routeName: 'SignIn' });
AsyncStorage.clear().then(() => {
  this.props.navigation.navigate('Auth', {}, subAction);

});

ADDING EXTRA SCRIPT

Current TabHelper script:-

const tabScreen = createBottomTabNavigator(
    {
        'Home': {screen: HomeStack},
        'Favourite': {screen: FavouriteScreen},
        'Cart': {screen: CartStack},
        'Profile': {screen: profileStack}
    },
    {
        initialRouteName: 'Home',
        headerMode: 'none',
        backBehavior: 'initialRoute',
        defaultNavigationOptions: ({ navigation }) => ({
            tabBarOnPress: ({ navigation, defaultHandler }) => {
                navigation.popToTop();
                defaultHandler();
            },
        }),
    }
);
const AppContainer = createAppContainer(tabScreen);
var screen = '';
let isExit = true;
let lastBackPressed = null;
export default class tabHelper extends Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        lastBackPressed = null;
    }

    onBackAndroid() {
        if (isExit) {
            if (lastBackPressed && lastBackPressed + 2000 >= Date.now()) {
                BackHandler.exitApp();
                return true;
            }
            lastBackPressed = Date.now();
            ToastAndroid.show('Press again to exit the app', ToastAndroid.SHORT);
            return true;
        }
        return false
    }
    getActiveRouteName(navigationState) {
        if (!navigationState) {
          return null;
        }
        const route = navigationState.routes[navigationState.index];
        if (route.routes) {
          return this.getActiveRouteName(route);
        }
        return route.routeName;
      } 
    render() {
        return <AppContainer onNavigationStateChange={(prevNav, nav, action) => {
            screen = this.getActiveRouteName(nav)
            var routes = nav.routes;
            var currentRoutes = routes[routes.length - 1];
            if (screen === 'MainHome') {
                if (currentRoutes.routes[currentRoutes.index].index == undefined || currentRoutes.routes[currentRoutes.index].index == 0) {
                    isExit = true;
                } else {
                    isExit = false;
                }
            } else {
                isExit = false;
            }
        }} ref={navigatorRef => {
            NavigationService.setTopLevelNavigator(navigatorRef);
        }} />
    }
}

FOUND SOMETHING:- On TabHelper file, if I remove const AppContainer = createAppContainer(tabScreen); onwards (use to handle backbutton on HomeScreen at focus) and replace with export default createAppContainer(tabScreen);, I can logout and navigate to Sign-In. It's like I need to choose one.

How do I have both of features? Handling backbutton for "Press again to exit" and logout navigation at tab helper?

Luiey
  • 843
  • 2
  • 23
  • 50

2 Answers2

0

try this , you need to go to screen rather than stack , or if you have defaultRoute in your stack then it hsould navigate there :

this.props.navigation.navigate('SignIn');

Hope it helps .fee lfree for doubts

Gaurav Roy
  • 11,175
  • 3
  • 24
  • 45
  • I also have try this, unfortunately nothing happen. If I navigate to other stack alongside tab e.g. Home, Cart even Home stack, it can navigate properly. – Luiey Feb 04 '20 at 07:50
0

I think u forgot to import navigation.

import {withNavigation} from “react-navigation”

export default withNavigation(ComponentName);

Also I recommend u not to use asyncstorage, and use expo Secure Store instead.

Update

onPress={()=>this.props.navigation.navigate(“auth”)}
  • I just tried your suggestion. Still nothing happen when click confirm logout. Currently, I'm storing just a base64 number in asyncstorage. i will go for another way to secure my local storage data in future project. – Luiey Feb 04 '20 at 08:41
  • Updated. Try from the callback. – Denis Bykov Feb 04 '20 at 11:07
  • I have update my question on **FOUND SOMETHING** part. The navigation cannot be done if I use backbutton handler in tabhelper. – Luiey Feb 05 '20 at 01:45