diff options
Diffstat (limited to 'src/providers')
| -rw-r--r-- | src/providers/AppProviders.tsx | 10 | ||||
| -rw-r--r-- | src/providers/AppProviders.tsx~ | 0 | ||||
| -rw-r--r-- | src/providers/AuthProvider.tsx | 51 | ||||
| -rw-r--r-- | src/providers/AuthProvider.tsx~ | 0 |
4 files changed, 61 insertions, 0 deletions
diff --git a/src/providers/AppProviders.tsx b/src/providers/AppProviders.tsx new file mode 100644 index 0000000..5246a42 --- /dev/null +++ b/src/providers/AppProviders.tsx @@ -0,0 +1,10 @@ +import React from 'react'; +import { AuthProvider } from './AuthProvider'; + +type AppProvidersProps = { + children: React.ReactNode; +}; + +export function AppProviders({ children }: AppProvidersProps) { + return <AuthProvider>{children}</AuthProvider>; +} diff --git a/src/providers/AppProviders.tsx~ b/src/providers/AppProviders.tsx~ new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/src/providers/AppProviders.tsx~ 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; +} diff --git a/src/providers/AuthProvider.tsx~ b/src/providers/AuthProvider.tsx~ new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/src/providers/AuthProvider.tsx~ |