1
votes

My react-native app allows people to use it without logging in, but some screens require the user to be logged in to access. I'm using react-navigation, and when an unauthenticated user navigates to one of these screens, I want to redirect to the log in screen.

Right now, the screen simply renders differently for a logged out user, but ideally it would not render at all (just redirect):

import { connect } from 'react-redux';

import ProfileScreen from './ProfileScreen';

const mapStateToProps = (state) => {
  const { currentUser } = state;

  return {
    currentUser,
  };
};

export default connect(mapStateToProps)(ProfileScreen);


// ProfileScreen.js
import React from 'react';
import { Text } from 'react-native';

const ProfileScreen = (props) => {
  if (props.currentUser == null) {
    return <Text>You are not logged in</Text>;
  }

  return <Text>Your Profile</Text>;
};

export default ProfileScreen;

Where is the proper place to put the redirect? I'm also using redux, so I've seen suggestions to put it in the componentDidMount of the container, or somewhere in the redux chain.

1
Hi. A chance that you could share an example of the full implementation ? - Pi Home Server

1 Answers

0
votes

Yes, you should keep a check in your ProfileScreen component's componentDidUpdate method to detect whether there is a currentUser in your redux store.

When the user is logged out, simply reset the navigation state to Login screen. In your component's componentDidUpdate,

componentDidUpdate(prevProps){
   if(!this.props.currentUser){
      const resetAction = StackActions.reset({
            index: 0,
            actions: [NavigationActions.navigate({ routeName: 'Login' })],
       });
      this.props.navigation.dispatch(resetAction);
  }
}

This will reset the navigation state and navigate to Login screen.

PS. If your Login screen is in another stack, add prop key:null in the resetAction params. This will reset the main app navigator and then navigate to Login screen.