Created
October 6, 2017 20:00
-
-
Save kaueDM/5e0abf244880066074fb2e73331f1346 to your computer and use it in GitHub Desktop.
This file contains hidden or 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, { Component } from 'react'; | |
import { connect } from 'react-redux'; | |
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom'; | |
import { auth } from '../services/firebase'; | |
import { | |
Login, | |
Home, | |
E404, | |
Dashboard | |
} from '../components'; | |
function PrivateRoute({ component: Component, authed, ...rest }) { | |
return ( | |
<Route | |
{...rest} | |
render={(props) => authed === true | |
? <Component {...props} /> | |
: <Redirect to={{ pathname: '/', state: { from: props.location } }} />} | |
/> | |
) | |
} | |
// function PublicRoute({ component: Component, authed, ...rest }) { | |
// return ( | |
// <Route | |
// {...rest} | |
// render={(props) => authed === false | |
// ? <Component {...props} /> | |
// : <Redirect to='/home' />} | |
// /> | |
// ) | |
// } | |
class MainRouter extends Component { | |
state = { authed: false } | |
componentDidMount() { | |
this.removeListener = auth.onAuthStateChanged(user => { | |
if (user) return this.setState({ authed: true }) | |
if (!user) return this.setState({ authed: false }) | |
}) | |
} | |
componentWillUnmount() { | |
this.removeListener() | |
} | |
render() { | |
return ( | |
<Router> | |
<Switch> | |
<Route exact path='/' component={Login} /> | |
<PrivateRoute exact path='/home' component={Home} authed={this.state.authed}> | |
<Route path="/dashboard" component={Dashboard} /> | |
</PrivateRoute> | |
{/* Wildcard */} | |
<Route path='*' component={E404} /> | |
</Switch> | |
</Router> | |
); | |
} | |
} | |
const mapStateToProps = state => { | |
const { user } = state.auth; | |
return { user }; | |
} | |
export default connect(mapStateToProps, null)(MainRouter) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment