Skip to content

Instantly share code, notes, and snippets.

@MoranggNormal
Created June 26, 2021 03:41
Show Gist options
  • Save MoranggNormal/b53c2cdb6589ca188d692287d18746fc to your computer and use it in GitHub Desktop.
Save MoranggNormal/b53c2cdb6589ca188d692287d18746fc to your computer and use it in GitHub Desktop.
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