0

While migrating our Onsen v1 app (based on AngularJS1) to Onsen v2 with React, I bumped into a little problem: implementing logic regarding user authentication (redirecting to login screen if there are no "saved credentials")

Here's how my app is structured...

Entry point is the App.js file, which looks like this:

import React from 'react';

import {Navigator} from 'react-onsenui';

import Home from './Home';
import Login from './Login';

class App extends React.Component {

    renderPage(route, navigator) {
        route.props = route.props || {};
        route.props.key = route.comp.displayName;
        route.props.navigator = navigator;
        return React.createElement(route.comp, route.props);
    }

    render() {
        return (
            <Navigator
                initialRoute={{comp: Home}}
                renderPage={this.renderPage}
            />
        );
    }
}

export default App;

You can see that I have my references for both 'Home' and 'Login' components, however, I want to decide which component to render.

I tried the following: use 'Home' as the initialRoute, and decide in the Home components constructor if we need to go to the Login page.

constructor(props) {
    super(props);
    this.state = {
        isOpen: false
    };
    const authenticated = GetAuthenticated();
    if(!authenticated) {
       this.props.navigator.pushPage({comp: Login});
    }
}

This simply did not work, the Login page was never shown.

So basically, what I would like to do is to look in the localStorage for user credentials (or any other place for storing these kind of information), and based on this decide whether to load up the 'Home' page or the 'Login' page.

Laureant
  • 979
  • 3
  • 18
  • 47

1 Answers1

0

If GetAuthenticated() is a fetch call you need to remember it acts asynchronously. I'd recommend a loading section whilst the fetch is pending and then a decision on the result of the method.

This link is a good example of how you can use componentDidMount to demonstrate pending async calls. Once that is implemented you can go on to do your switch.

DO NOT, and I can't stress this enough, store user credentials in localStorage ever. Never ever.

Tubs
  • 717
  • 9
  • 18
  • Hi! Thanks for the reply. I tried using the componentDidMount, however when I'm trying to pass the "Login" component as a parameter to the navigator object, it says "Login is not defined". Any ideas why this could happen? – Laureant Apr 05 '18 at 13:43
  • Can you edit the OP with the code you attempted for `componentDidMount` as it could be any number of things – Tubs Apr 06 '18 at 08:12