简体   繁体   中英

Flux + React.js Login/register flow

I'm looking for some guide how to organize best login/registration flow in my Flux+React.js app.

What I have is a REST API which while registration/login returns access_token which I can use in all other requests to get user data. Very basic.

I'm using ReactRouter and what comes to mind firstly is to use 2 <Route> 's for login pages and for secured ones, eg:

<Route name="app" handler={AppHandler} path="/">
  <Route name="auth" handler={AuthHandler}>
    <Route name="login" handler={RegisterHandler} path="/register"/>
    <Route name="register" handler={LoginHandler} path="/login"/>
  </Route>
  <Route name="secured" handler={EnsureAuthHandler}>
    <Route name="dashboard" handler={Dashboard} />
  </Route>
  <NotFoundRoute handler={NotFound}/>
</Route>

Inside EnsureAuthHandler I want to check if user has access token, if "NO" I would like to redirect him to login, if "YES" children route handler can fire actions to load its' data.

Inside RegisterHandler and LoginHandler I have forms with several fields. I'm using one AuthStore and one AuthActions files. On submit I'm firing smth like AuthActions.register(formData) and if submit fails form component gets errors to state from AuthStore but if no errors happen I redirect user to Dashboard .

I'm feeling like it's a bit overcomplicated? For example using stores to save errors of login/register.

Another point, how to intercept unauthorized API error in one place, addListener to Flux dispatcher?

You can use callback function in React.run point of your application:

// Defaults to `Router.HashLocation`
// callback is called whenever the hash changes
Router.run(routes, callback);

// HTML5 History
// callback is called when history events happen
Router.run(routes, Router.HistoryLocation, callback);

// Server rendering
// callback is called once, immediately.
Router.run(routes, '/some/path', callback);

Which receives two arguments:

  1. Root
  2. state

Root - A ReactComponent class with the current match all wrapped up inside it, ready for you to render.

state - An object containing the matched state.

Just go to http://rackt.github.io/react-router/#Router.run

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM