Skip to content

Instantly share code, notes, and snippets.

@ortonomy
Last active March 6, 2020 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ortonomy/516ce47eb20ccd744b4874757d83032c to your computer and use it in GitHub Desktop.
Save ortonomy/516ce47eb20ccd744b4874757d83032c to your computer and use it in GitHub Desktop.
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