Skip to content

Instantly share code, notes, and snippets.

@PierBover

PierBover/Main.jsx

Created Jul 16, 2016
Embed
What would you like to do?
JWT Auth React Router async wait
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'))
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>
)
}
}
@PierBover

This comment has been minimized.

Copy link
Owner Author

@PierBover PierBover commented Jul 16, 2016

I didn't test this exact code, but you get the idea...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.