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