Created
March 2, 2022 13:10
-
-
Save leighhalliday/e5b1b41ba4a23542adbc2fc17439d276 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 { | |
| useEffect, | |
| useState, | |
| useContext, | |
| createContext, | |
| FunctionComponent, | |
| } from "react"; | |
| import { firebase } from "./initFirebase"; | |
| const AuthContext = createContext({ | |
| user: null, | |
| loading: true, | |
| logout: () => {}, | |
| }); | |
| const AuthProvider = ({ children }) => { | |
| const [user, setUser] = useState(null); | |
| const [loading, setLoading] = useState(true); | |
| useEffect(() => { | |
| const cancelAuthListener = firebase.auth().onIdTokenChanged((u) => { | |
| setUser(u); | |
| setLoading(false); | |
| }); | |
| return () => cancelAuthListener(); | |
| }, []); | |
| return ( | |
| <AuthContext.Provider | |
| value={{ user, loading, logout: () => firebase.auth().signOut() }} | |
| > | |
| {children} | |
| </AuthContext.Provider> | |
| ); | |
| }; | |
| function useAuth() { | |
| return useContext(AuthContext); | |
| } | |
| export { AuthProvider, useAuth }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment