Skip to content

Instantly share code, notes, and snippets.

@xergiodf
Created December 4, 2020 13:01
Show Gist options
  • Select an option

  • Save xergiodf/47a916997741c960ac0d31c6f5a59ed0 to your computer and use it in GitHub Desktop.

Select an option

Save xergiodf/47a916997741c960ac0d31c6f5a59ed0 to your computer and use it in GitHub Desktop.
import React, { useCallback, useState, useEffect, useContext, createContext } from 'react'
const authContext = createContext()
// Hook for child components to get the auth object and re-render when it changes.
export default () => {
return useContext(authContext)
}
// Provider component that wraps components and makes useAuth() available
export function ProvideAuth({ children }) {
const auth = useAuthProvider()
return <authContext.Provider value={auth}>{children}</authContext.Provider>
}
// Provide Auth hook that creates auth object and handles state
function useAuthProvider() {
const [user, setUser] = useState(null)
// Get the logged in user when created
useEffect(() => {
const user = getLoggedInUser()
setUser(user)
}, [])
const login = async (...) => {
const user = ...
setUser(user)
}
const logout = async () => {
...
setUser(null)
}
const resetPassword = async () => {
...
}
return {
resetPassword
login,
logout,
user
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment