Call stack exceeded when using react-router in an auth pattern -


i'm using react-router rc6 in following auth pattern:

const isloggedin = false  function requireauth (nextstate, replacestate) {   console.log(nextstate.location.pathname)   if(!isloggedin) {     replacestate({ nextpathname: nextstate.location.pathname }, '/login')   } }  reactdom.render((   <router history={browserhistory}>     <route path='/' component={main} onenter={requireauth}>       <route path='login' component={login} />     </route>   </router> ), document.getelementbyid('app')); 

i've seen common pattern, according https://github.com/rackt/react-router/issues/2773, can't redirect in onenter hook because function requireauth above gets called in infinite loop. how should instead? want redirect /login page if not authenticated.

this because / onenter handler tries redirect route executes same / onevent handler.

i.e. happens is:

  1. router tries handle request / (first match of /login).
  2. / has onenter handler. handler executed.
  3. handler wants navigate /login.
  4. router tries handle request / (back step 1).

so can see, reason why getting call stack exceeded error because circular.

try change routes following:

reactdom.render((   <router history={browserhistory}>     <route path='/' component={main}>       <route path='/login' component={login} />       <route path='/user' onenter={requireauth}>         <route path='/profile' component={profile}>       </route>     </route>   </router> ), document.getelementbyid('app')); 

this way routes require authentication protected behind requireauth handler.

if you'd rather have simple auth solution react, take @ react sdk stormpath i've built.

it take care of of this. , instead of having use hacky onenter handlers, need use sdk's authenticatedroute. e.g.

<router history={createbrowserhistory()}>   <homeroute path='/' component={masterpage}>     <indexroute component={indexpage} />     <loginroute path='/login' component={loginpage} />     <logoutroute path='/logout' />     <route path='/verify' component={verifyemailpage} />     <route path='/register' component={registerpage} />     <route path='/forgot' component={resetpasswordpage} />     <authenticatedroute>       <homeroute path='/profile' component={profilepage} />     </authenticatedroute>   </homeroute> </router> 

the example above real-world example extracted react sdk example project. see: https://github.com/stormpath/stormpath-express-react-example/blob/master/src/app.js#l11-l23.

let me know if helped you.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -