Last active
February 12, 2018 19:43
-
-
Save stevenkaspar/911232c3b86533744d23a6d937b5aeda to your computer and use it in GitHub Desktop.
React HOC Logout - Apollo Example
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 from 'react'; | |
import { withApollo } from 'react-apollo' | |
// will add a logout function to this.props when used around a component | |
// i.e. | |
// export default logout(LogoutButton) | |
const logout = function(WrappedComponent) { | |
class Logout extends React.Component { | |
constructor(props) { | |
super() | |
this.handleLogout = this.handleLogout.bind(this) | |
} | |
handleLogout(event) { | |
return new Promise((resolve, reject) => { | |
try { | |
localStorage.removeItem('jwt-token') | |
this.props.client.resetStore() | |
resolve() | |
} | |
catch(err) { | |
reject(err) | |
} | |
}) | |
} | |
render() { | |
return <WrappedComponent logout={this.handleLogout} {...this.props} /> | |
} | |
} | |
return withApollo(Logout) | |
} | |
export default logout |
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 from 'react' | |
import logout from 'logout' | |
class Header extends React.Component { | |
constructor() { | |
super() | |
this.handleLogout = this.handleLogout.bind(this) | |
} | |
handleLogout() { | |
// we have this prop because of the logout(...) HOC | |
this.props.logout().then(() => window.location.href = '/home') | |
} | |
render() { | |
return ( | |
<div> | |
<button onClick={this.handleLogout}>Logout</button> | |
</div> | |
) | |
} | |
} | |
export default logout(Header) |
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 from 'react' | |
import logout from 'logout' | |
const Header = (props) => ( | |
<div> | |
<button onClick={props.logout}>Logout</button> | |
</div> | |
) | |
export default logout(Header) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment