Created
July 16, 2016 01:13
-
-
Save PierBover/220b2f7d5f790158790d3adb55f0a140 to your computer and use it in GitHub Desktop.
JWT Auth React Router async wait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
render(( | |
<div> | |
<Router history={browserHistory}> | |
<Route path="/" component={App}> | |
<IndexRoute component={Start}/> | |
<Route path="login" component={Login}/> | |
// Everything inside Main is private | |
<Route component={Main}> | |
<Route path="home" component={Home}/> | |
<Route path="setting" component={Settings}/> | |
// etc | |
</Route> | |
</Route> | |
<Route path="*" component={Ooops}/> | |
</Router> | |
</div> | |
), document.getElementById('app-react')) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
export default class Main extends React.Component { | |
constructor(props){ | |
super(props) | |
this.state = {} | |
} | |
componentWillMount(){ | |
this.checkAuth() | |
} | |
checkAuth(){ | |
// Here we do stuff to check if the user is already logged in or not | |
// Since we are using Firebase with JWT it takes a bit to know if a user | |
// is logged or not. | |
// This is our own specific implementation so stateManager and eventBus are our own | |
let isLogged = this.stateManager.getState('isLogged') | |
if(isLogged == undefined){ | |
this.eventBus.addListener(this.events.auth.loggedIn,this.checkAuth,this) | |
this.eventBus.addListener(this.events.auth.loggedOut,this.checkAuth,this) | |
} else { | |
this.eventBus.removeListener(this.events.auth.loggedIn,this.checkAuth,this) | |
this.eventBus.removeListener(this.events.auth.loggedOut,this.checkAuth,this) | |
// Once we have a known state of either logged in or out we can show the children | |
this.setState({ | |
showChildren:true | |
}) | |
// And redirect appropirately | |
this.redirect(isLogged) | |
} | |
} | |
redirect(isLogged){ | |
if(isLogged) { | |
// If the user is logged we push the actual path again so the Main component loads again | |
this.history.push(this.props.location.pathname) | |
} else { | |
//If not we send the user to the login form | |
this.history.push('/login') | |
} | |
} | |
render(){ | |
return( | |
<div> | |
{this.state.showChildren ? this.props.chidlren : null} | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I didn't test this exact code, but you get the idea...