From 55123c62cc1a66d470cf8b46a3201c35f8d39e86 Mon Sep 17 00:00:00 2001 From: Atul Varma Date: Sun, 22 Aug 2021 09:05:24 -0400 Subject: [PATCH] Eh, just move all the firebase stuff into FirebaseContext. --- lib/firebase.tsx | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/lib/firebase.tsx b/lib/firebase.tsx index 344c17e..29af6fe 100644 --- a/lib/firebase.tsx +++ b/lib/firebase.tsx @@ -21,12 +21,14 @@ const DEFAULT_APP_CONFIG: FirebaseOptions = { measurementId: "G-JHKRSK1PR6", }; -type FirebaseGithubAuthState = { +type FirebaseAppContext = { + app: FirebaseApp; auth: Auth; provider: GithubAuthProvider; }; -export const FirebaseAppContext = React.createContext(null); +export const FirebaseAppContext = + React.createContext(null); /** * A Firebase app provider. Any other components that use Firebase must @@ -39,13 +41,17 @@ export const FirebaseAppProvider: React.FC<{ config?: FirebaseOptions }> = ({ config, children, }) => { - const [app, setApp] = useState(null); + const [value, setValue] = useState(null); useEffect(() => { - setApp(initializeApp(config || DEFAULT_APP_CONFIG)); + const app = initializeApp(config || DEFAULT_APP_CONFIG); + const auth = getAuth(app); + const provider = new GithubAuthProvider(); + + setValue({ app, auth, provider }); }, [config]); - return ; + return ; }; /** @@ -55,34 +61,31 @@ export const FirebaseAppProvider: React.FC<{ config?: FirebaseOptions }> = ({ * Note this component is assumed to never be unmounted. */ export const FirebaseGithubAuthProvider: React.FC<{}> = ({ children }) => { - const app = useContext(FirebaseAppContext); - const [state, setState] = useState(null); + const appCtx = useContext(FirebaseAppContext); const [user, setUser] = useState(null); const [error, setError] = useState(undefined); const handleError = (e: Error) => setError(e.message); useEffect(() => { - if (!app) return; - const auth = getAuth(app); - const provider = new GithubAuthProvider(); + if (!appCtx) return; - setState({ auth, provider }); - onAuthStateChanged(auth, setUser); - }, [app]); + onAuthStateChanged(appCtx.auth, setUser); + }, [appCtx]); const context: AuthContext = { loggedInUser: user && user.displayName, - providerName: state && "GitHub", + providerName: appCtx && "GitHub", error, login: useCallback(() => { setError(undefined); - state && signInWithPopup(state.auth, state.provider).catch(handleError); - }, [state]), + appCtx && + signInWithPopup(appCtx.auth, appCtx.provider).catch(handleError); + }, [appCtx]), logout: useCallback(() => { setError(undefined); - state && signOut(state.auth).catch(handleError); - }, [state]), + appCtx && signOut(appCtx.auth).catch(handleError); + }, [appCtx]), }; return ;