diff --git a/src/contexts/AuthContext.tsx b/src/contexts/AuthContext.tsx new file mode 100644 index 0000000..574c18d --- /dev/null +++ b/src/contexts/AuthContext.tsx @@ -0,0 +1,53 @@ +import React, { createContext, useContext, useEffect, useState } from 'react'; +import { Session, User } from '@supabase/supabase-js'; +import { supabase } from '../lib/supabase'; + +interface AuthContextType { + session: Session | null; + user: User | null; + isLoading: boolean; + signOut: () => Promise; +} + +const AuthContext = createContext({ + session: null, + user: null, + isLoading: true, + signOut: async () => {}, +}); + +export const useAuth = () => useContext(AuthContext); + +export const AuthProvider = ({ children }: { children: React.ReactNode }) => { + const [session, setSession] = useState(null); + const [user, setUser] = useState(null); + const [isLoading, setIsLoading] = useState(true); + + useEffect(() => { + supabase.auth.getSession().then(({ data: { session } }) => { + setSession(session); + setUser(session?.user ?? null); + setIsLoading(false); + }); + + const { data: { subscription } } = supabase.auth.onAuthStateChange( + (_event, session) => { + setSession(session); + setUser(session?.user ?? null); + setIsLoading(false); + } + ); + + return () => subscription.unsubscribe(); + }, []); + + const signOut = async () => { + await supabase.auth.signOut(); + }; + + return ( + + {children} + + ); +};