Skip to content
Advertisement

React native – prevent user from going back to login screen

I’ve created a Login button using Facebook SDK. Once the user is logged in, the app navigates to the second screen (NavigatorIOS). From that second screen the user can go back to the login screen using the navigation (back button).

How can I prevent the user from going back to the Login screen if he is already logged in?

index.ios.js

import React, { Component } from 'react'

import {
  AppRegistry,
  StyleSheet,
  NavigatorIOS
} from 'react-native'

import LoginView from './src/login-view'

class MyApp extends Component {
  render() {
    return (
      <Provider store={store}>
        <NavigatorIOS
          initialRoute={{
            component: LoginView,
            title: 'MyApp',
            index: 0
          }}
        />
      </Provider>
    );
  }
}
AppRegistry.registerComponent('MyApp', () => MyApp);

LoginView

import React, {Component} from 'react'
import {
    View,
    Text,
    StyleSheet,
    TouchableHighlight,
} from 'react-native'

import CategoryView from './category-view'

import {LoginButton, AccessToken, GraphRequest, GraphRequestManager} from 'react-native-fbsdk'

class LoginView extends Component {
    goToCategoryView = () =>
        this.props.navigator.push({
            title: 'Categories',
            component: CategoryView,
        })

    render(){
        return(
            <View style={styles.container}>
                <LoginButton
                    readPermissions={['public_profile','email']}
                    onLoginFinished={
                        (error, result) => {
                            if (error) {
                                console.log('login has error: ', result.error)
                            } else if (result.isCancelled) {
                                console.log('login is cancelled.')
                            } else {
                                AccessToken.getCurrentAccessToken().then((data) => {    
                                    this.goToCategoryView()
                                })
                            }
                        }
                    }
                    onLogoutFinished={() => {console.log('logged out')}} />
            </View>
        )
    }
}

export default LoginView

Advertisement

Answer

Using Navigator, you can use resetTo(startingRoute) method to reset the stack and start a new one from the route you past as a parameter. Doing this you will prevent to navigate back in the stack.

If I’m not misunderstanding your component, you should use something like this:

goToCategoryView = () => {
    //Replace here push with resetTo
    this.props.navigator.resetTo({
        title: 'Categories',
        component: CategoryView,
    })
}

Facebook Docs

Advertisement