Last active
July 19, 2018 19:28
-
-
Save joelosx/89719b4f848936a5e1ab0ae8d94d51f9 to your computer and use it in GitHub Desktop.
AuthExample.js
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
// | |
// AuthExample.js | |
// | |
import React from 'react'; | |
import { | |
BrowserRouter as Router, | |
Route, | |
Link, | |
Redirect, | |
withRouter, | |
} from 'react-router-dom' | |
const fakeAuth = { | |
isAuthenticated: false, | |
authenticate(cb) { | |
this.isAuthenticated = true | |
setTimeout(cb,500) | |
}, | |
signout(cb) { | |
this.isAuthenticated = false | |
setTimeout(cb,100) | |
} | |
} | |
const Public = () => <h3>Publc</h3> | |
const Protected = () => <h3> Protected </h3> | |
class Login extends React.Component { | |
state = { | |
redirectToReferrer: false | |
} | |
login = () => { | |
fakeAuth.authenticate(() => { | |
this.setState(() => ({ | |
redirectToReferrer: true | |
})) | |
}) | |
} | |
render() { | |
const { from } = this.props.location.state || {from: { pathname: '/'} } | |
const { redirectToReferrer } = this.state | |
if (redirectToReferrer === true) { | |
return <Redirect to={from} /> // <-- Problems seems to be here - | |
} // from: {pathname: "/protected", search: "", hash: "", state: undefined, key: "g60r1z"} | |
return ( | |
<div> | |
<p> You must log in to view the page</p> | |
<button onClick={this.login} > Log in </button> | |
</div> | |
) | |
} | |
} | |
const PrivateRoute = ({component: Component, ...rest}) => ( | |
<Route {...rest} render = {(props) => ( | |
fakeAuth.isAuthenticated === true | |
? <Component {...props} /> | |
: <Redirect to={{ | |
pathname: '/login', | |
state: { from: props.location } | |
}} /> | |
)} /> | |
) | |
const AuthButton = withRouter(({history}) =>( | |
fakeAuth.isAuthenticated ? ( | |
<p> | |
Welcome! <button onClick={() => { | |
fakeAuth.signout(() => history.push('/')) | |
}} >Sign Out</button> | |
</p> | |
) : ( | |
<p>You are not logged in. </p> | |
) | |
)) | |
export default function AuthExample() { | |
return ( | |
<Router> | |
<div> | |
<AuthButton /> | |
<ul> | |
<li><Link to="/public">Public Page</Link></li> | |
<li><Link to="/protected">Protected Page </Link></li> | |
</ul> | |
<Route path="/public" component={Public} /> | |
<Route path="/login" component={Login} /> | |
<PrivateRoute path="/protected" component={Protected} /> | |
</div> | |
</Router> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Adding the "return" statement on line 44 seems to have fixed the problem....