Add AuthProvider tracking Supabase session
This commit is contained in:
31
frontend/src/auth/AuthProvider.tsx
Normal file
31
frontend/src/auth/AuthProvider.tsx
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
|
||||||
|
import type { Session } from '@supabase/supabase-js';
|
||||||
|
import { supabase } from '../lib/supabase';
|
||||||
|
|
||||||
|
type AuthContextValue = {
|
||||||
|
session: Session | null;
|
||||||
|
loading: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const AuthContext = createContext<AuthContextValue>({ session: null, loading: true });
|
||||||
|
|
||||||
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [session, setSession] = useState<Session | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const { data } = supabase.auth.onAuthStateChange((_event, s) => {
|
||||||
|
setSession(s);
|
||||||
|
setLoading(false);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
data.subscription.unsubscribe();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return <AuthContext.Provider value={{ session, loading }}>{children}</AuthContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAuth() {
|
||||||
|
return useContext(AuthContext);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user