Skip to content

Instantly share code, notes, and snippets.

@allpwrfulroot
Last active September 29, 2020 13:34
Show Gist options
  • Save allpwrfulroot/090ceee5e60baaf5bad8e65582af9ab8 to your computer and use it in GitHub Desktop.
Save allpwrfulroot/090ceee5e60baaf5bad8e65582af9ab8 to your computer and use it in GitHub Desktop.
AuthProvider using React Context and providing a simple hook
import React, { createContext, useContext, useState, useEffect } from 'react'
import { useRouter } from 'next/router'
const AuthContext = createContext()
function AuthProvider({ children }) {
const { pathname, events } = useRouter()
const [user, setUser] = useState()
async function getUser() {
try {
const response = await fetch('/api/me')
const profile = await response.json()
if (profile.error) {
setUser(null)
} else {
setUser(profile)
}
} catch (err) {
console.error(err)
}
}
useEffect(() => {
getUser()
}, [pathname])
useEffect(() => {
// Check that a new route is OK
const handleRouteChange = url => {
if (url !== '/' && !user) {
window.location.href = '/'
}
}
// Check that initial route is OK
if (pathname !== '/' && user === null) {
window.location.href = '/'
}
// Monitor routes
events.on('routeChangeStart', handleRouteChange)
return () => {
events.off('routeChangeStart', handleRouteChange)
}
}, [user])
return (
<AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
)
}
const useAuth = () => useContext(AuthContext)
export { AuthProvider, useAuth }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment