Shrouk H. Khan Shrouk H. Khan - 3 months ago 35
React JSX Question

React Native - How to Redirect to a login view from componentWillReceiveProps

I am trying to detect if a user is logged in during an application start and redirect him to a login screen if not logged in.

import * as AuthView from '../modules/auth/AuthView';
const AppView = React.createClass({
propTypes: {
isReady: PropTypes.bool.isRequired,
isLoggedIn: PropTypes.bool.isRequired,
dispatch: PropTypes.func.isRequired
},
componentDidMount() {
snapshotUtil.resetSnapshot()
.then(snapshot => {
const {dispatch} = this.props;

if (snapshot) {
dispatch(SessionStateActions.resetSessionStateFromSnapshot(snapshot));
} else {
dispatch(SessionStateActions.initializeSessionState());
}

store.subscribe(() => {
snapshotUtil.saveSnapshot(store.getState());
});
});
},

componentWillReceiveProps({isReady, isLoggedIn}) {
if (!this.props.isReady) {
if (isReady && !isLoggedIn) {
console.warn("Not logged in, trying to show login screen here...");
AuthView.showLoginView();
}
}
},

render() {
if (!this.props.isReady) {
return (
<View>
<ActivityIndicator style={styles.centered}/>
</View>
);
}
return (
<View style={{flex: 1}}>
<NavigationViewContainer />
</View>
);
}
});


And my AuthView Looks like this:

export function showLoginView() {
var loginView = <View>
<Text>
This is a Login View
</Text>
</View>;

return loginView;
}


The output is blank . looks like this : http://i.imgur.com/6CgvOGW.png

So it is showing the warning message ( console.warn ) and showing the "ActivityIndicator" . But not a Login Panel.

My question is, how to I modify the showLoginView() function to show a full screen login view?

Answer

You have to show all views within your render() function. If you develop a complex application consider use Navigator component. In your case:

 componentWillReceiveProps({isReady, isLoggedIn}) {
    if (!this.props.isReady) {
        if (isReady && !isLoggedIn) {
            console.warn("Not logged in, trying to show login screen here...");
           this.state.showLogin = true;
        }
    }
 },
 render() {
    if (this.state.showLogin) {
        return showLoginView()
    } 
    if (!this.props.isReady) {
        return (
            <View>
                <ActivityIndicator style={styles.centered}/>

...

Comments