Skip to content

Instantly share code, notes, and snippets.

@codinronan
Created November 29, 2020 03:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codinronan/10614c58adbf71bee4ceda3623e7e7dd to your computer and use it in GitHub Desktop.
Save codinronan/10614c58adbf71bee4ceda3623e7e7dd to your computer and use it in GitHub Desktop.
React hook: useAuth
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