Last active
March 6, 2020 03:18
-
-
Save ortonomy/516ce47eb20ccd744b4874757d83032c 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 from 'react' | |
import { withRouter } from 'next/router' | |
export const AuthContext = React.createContext({ | |
isAuthenticated: false, | |
token: null, | |
user: null, | |
}) | |
/** | |
* This app doesn't care about restricted routes -- all pages are always visitble | |
* However, the article pages in particular care if the user is logged in so we can show a pay wall | |
* after they've read 2 articles. | |
*/ | |
class AuthProvider extends React.Component { | |
state = { | |
isAuthenticated: false, | |
token: null, | |
user: null, | |
setIsAuthenticated: this.setIsAuthenticated, | |
setToken: this.setToken, | |
} | |
updateState = objProp => (value = null) => { | |
this.setState(state => { | |
return { | |
...state, | |
objProp: value, | |
} | |
}) | |
} | |
setIsAuthenticated = this.updateState('isAuthenticated') | |
setToken = this.updateState('token') | |
checkAuth = () => { | |
const { router } = this.props | |
// check local storage for token and fill up state if it exists | |
// check validity ==> call API /profile | |
// set isAuthenticated state | |
} | |
componentDidMount = () => { | |
if ( process.browser ) { | |
this.checkAuth() | |
} | |
} | |
render() { | |
const { children } = this.props | |
return ( | |
<AuthContext.Provider value={this.state}>{children}</AuthContext.Provider> | |
) | |
} | |
} | |
export const AuthProviderWithRouter = withRouter(AuthProvider) | |
export const AuthConsumer = AuthContext.Consumer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment