Created
June 26, 2021 03:41
-
-
Save MoranggNormal/b53c2cdb6589ca188d692287d18746fc to your computer and use it in GitHub Desktop.
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 { createContext, ReactNode, useEffect, useState } from "react" | |
import { auth, firebase } from "../services/firebase" | |
type User = { | |
id: string | |
name: string | |
avatar: string | |
} | |
type AuthContextType = { | |
user: User | undefined | |
singInWithGoogle: () => Promise<void> | |
} | |
type AuthContextProviderProps = { | |
children: ReactNode | |
} | |
export const AuthContext = createContext({} as AuthContextType) | |
export function AuthContextProvider(props: AuthContextProviderProps) { | |
const [user, setUser] = useState<User>() | |
useEffect(() => { | |
const unsubscribe = auth.onAuthStateChanged(user => { | |
if (user) { | |
const { displayName, photoURL, uid } = user | |
if (!displayName || !photoURL) { | |
throw new Error('Missing information from Google Account.') | |
} | |
setUser({ | |
id: uid, | |
name: displayName, | |
avatar: photoURL | |
}) | |
} | |
}) | |
return () => { | |
unsubscribe() | |
} | |
}, [user]) | |
async function singInWithGoogle() { | |
const provider = new firebase.auth.GoogleAuthProvider() | |
const result = await auth.signInWithPopup(provider) | |
if (result.user) { | |
const { displayName, photoURL, uid } = result.user | |
if (!displayName || !photoURL) { | |
throw new Error('Missing information from Google Account.') | |
} | |
setUser({ | |
id: uid, | |
name: displayName, | |
avatar: photoURL | |
}) | |
} | |
} | |
return ( | |
<AuthContext.Provider value={{ user, singInWithGoogle }}> | |
{props.children} | |
</AuthContext.Provider> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment