Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

auth.tsx

72 lines1.7 KB

1import * as React from 'react'
2​
3import {
4 onAuthStateChanged,
5 type User,
6 type AuthProvider,
7 signInWithPopup,
8 signOut,
9} from 'firebase/auth'
10import { flushSync } from 'react-dom'
11import { auth } from './firebase/config'
12​
13export type AuthContextType = {
14 isAuthenticated: boolean
15 isInitialLoading: boolean
16 login: (provider: AuthProvider) => Promise<void>
17 logout: () => Promise<void>
18 user: User | null
20​
21const AuthContext = React.createContext<AuthContextType | null>(null)
22​
23export function AuthContextProvider({
24 children,
25}: {
26 children: React.ReactNode
27}) {
28 const [user, setUser] = React.useState<User | null>(auth.currentUser)
29 const [isInitialLoading, setIsInitialLoading] = React.useState(true)
30 const isAuthenticated = !!user
31​
32 React.useEffect(() => {
33 const unsubscribe = onAuthStateChanged(auth, (user) => {
34 flushSync(() => {
35 setUser(user)
36 setIsInitialLoading(false)
37 })
38 })
39 return () => unsubscribe()
40 }, [])
41​
42 const logout = React.useCallback(async () => {
43 console.log('Logging out...')
44 await signOut(auth)
45 setUser(null)
46 setIsInitialLoading(false)
47 }, [])
48​
49 const login = React.useCallback(async (provider: AuthProvider) => {
50 const result = await signInWithPopup(auth, provider)
51 flushSync(() => {
52 setUser(result.user)
53 setIsInitialLoading(false)
54 })
55 }, [])
56​
57 return (
58 <AuthContext.Provider
59 value={{ isInitialLoading, isAuthenticated, user, login, logout }}
60 >
61 {children}
62 </AuthContext.Provider>
63 )
65​
66export function useAuth() {
67 const context = React.useContext(AuthContext)
68 if (!context) {
69 throw new Error('useAuth must be used within an AuthProvider')
70 }
71 return context