How to prevent going back to login screen reactnative

1.6k Views Asked by At

Below are my login and index files,after login if back key is pressed it returns back to login. Im new to react native please advise.I am stuck with this past one week. I am using expo development

login.js

userLogin = () => {
if(this.state.email === '' && this.state.password === '') {
  Alert.alert('Enter details to signin!')
} else {
  this.setState({
    isLoading: true,
  })
  firebase
  .auth()
  .signInWithEmailAndPassword(this.state.email, this.state.password)
  .then((res) => {
    console.log(res)
    console.log('User logged-in successfully!')
    this.setState({
      isLoading: false,
      email: '', 
      password: ''
    })
    this.props.navigation.navigate('Deqo')
  })
  .catch(error => this.setState({ errorMessage: error.message }))
}
}

This is the navigation path. I navigated straight away from stack navigation to bottom tab navigation.

index.tsx

import { NavigationContainer, DefaultTheme, DarkTheme} from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import * as React from 'react';
import { ColorSchemeName } from 'react-native';


import BottomTabNavigator from './BottomTabNavigator';
import LinkingConfiguration from './LinkingConfiguration';

export default function Navigation({ colorScheme }: { colorScheme: ColorSchemeName }) {
return (
<NavigationContainer
  linking={LinkingConfiguration}
  theme={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
  
  <MyStack/>
</NavigationContainer>
);
}
2

There are 2 best solutions below

0
On

You need to create a switch navigator in such authentication flows. In case of stack navigator, react navigation creates a stack of routes by pushing new routes on it. In case of switch navigator, there will be complete new navigator stack created whenever you switches between those routes. For reference you can follow something that is mentioned as an example of react-navigation website https://reactnavigation.org/docs/4.x/auth-flow.

0
On

you can use navigation.reset() after you login directly. .reset() will clear all the history of navigation. and will start a new one from an index that you can specify. also you ll specify which screen stack you want to start the new stack navigation history with it. this is a snippet of my code. after the user login directly. I clear the history. and start from the mainLayout. so the user can never back to the login screen. just if he pressed a button that navigate to that screen:

  React.useEffect(() => {
if (user) {
  navigation.navigate("MainLayout");
  navigation.reset({
    index: 0,
    routes: [{ name: "MainLayout" }],
  });
}
}, [user]);