Created
November 29, 2020 03:26
-
-
Save codinronan/10614c58adbf71bee4ceda3623e7e7dd to your computer and use it in GitHub Desktop.
React hook: useAuth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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