google sign in page done
This commit is contained in:
68
src/contexts/AuthContext.tsx
Normal file
68
src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react'
|
||||
import {
|
||||
browserLocalPersistence,
|
||||
onAuthStateChanged,
|
||||
setPersistence,
|
||||
signInWithPopup,
|
||||
signOut as firebaseSignOut,
|
||||
type User,
|
||||
} from 'firebase/auth'
|
||||
import { auth, googleProvider } from '../lib/firebase'
|
||||
|
||||
type AuthContextValue = {
|
||||
user: User | null
|
||||
loading: boolean
|
||||
signInWithGoogle: () => Promise<void>
|
||||
signOut: () => Promise<void>
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null)
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = onAuthStateChanged(auth, (u) => {
|
||||
setUser(u)
|
||||
setLoading(false)
|
||||
})
|
||||
return () => unsubscribe()
|
||||
}, [])
|
||||
|
||||
async function signInWithGoogle() {
|
||||
await setPersistence(auth, browserLocalPersistence)
|
||||
await signInWithPopup(auth, googleProvider)
|
||||
}
|
||||
|
||||
async function signOut() {
|
||||
await firebaseSignOut(auth)
|
||||
}
|
||||
|
||||
const value: AuthContextValue = {
|
||||
user,
|
||||
loading,
|
||||
signInWithGoogle,
|
||||
signOut,
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={value}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext)
|
||||
if (ctx == null) {
|
||||
throw new Error('useAuth must be used within AuthProvider')
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
Reference in New Issue
Block a user