diff options
Diffstat (limited to 'src/providers/AuthProvider.tsx')
| -rw-r--r-- | src/providers/AuthProvider.tsx | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/providers/AuthProvider.tsx b/src/providers/AuthProvider.tsx new file mode 100644 index 0000000..edcc89c --- /dev/null +++ b/src/providers/AuthProvider.tsx @@ -0,0 +1,51 @@ +import React, { createContext, useContext, useEffect, useMemo, useState } from 'react'; +import { onAuthStateChanged, User } from 'firebase/auth'; +import { auth } from '@/shared/lib/firebase/config'; +import { authService } from '@/features/auth/services/authService'; + +type AuthContextValue = { + user: User | null; + loading: boolean; + logout: () => Promise<void>; +}; + +const AuthContext = createContext<AuthContextValue | undefined>(undefined); + +type AuthProviderProps = { + children: React.ReactNode; +}; + +export function AuthProvider({ children }: AuthProviderProps) { + const [user, setUser] = useState<User | null>(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + const unsubscribe = onAuthStateChanged(auth, (nextUser) => { + setUser(nextUser); + setLoading(false); + }); + + return unsubscribe; + }, []); + + const value = useMemo<AuthContextValue>( + () => ({ + user, + loading, + logout: authService.logout, + }), + [user, loading] + ); + + return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>; +} + +export function useAuthSession() { + const context = useContext(AuthContext); + + if (!context) { + throw new Error('useAuthSession must be used within AuthProvider'); + } + + return context; +} |