Created
December 4, 2020 13:01
-
-
Save xergiodf/47a916997741c960ac0d31c6f5a59ed0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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