Working frontend interface with supabse storage

This commit is contained in:
Harivansh Rathi 2024-12-05 17:05:20 -05:00
parent ae239a2849
commit 1eb339623c
19 changed files with 1150 additions and 422 deletions

View file

@ -0,0 +1,72 @@
import React, { createContext, useContext, useEffect, useState } from 'react';
import { Session, User, AuthError } from '@supabase/supabase-js';
import { auth } from '../lib/supabase';
interface AuthContextType {
session: Session | null;
user: User | null;
loading: boolean;
signIn: (email: string, password: string) => Promise<{ error: AuthError | null }>;
signUp: (email: string, password: string) => Promise<{ error: AuthError | null }>;
signOut: () => Promise<{ error: AuthError | null }>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [session, setSession] = useState<Session | null>(null);
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// Get initial session
auth.getSession().then(({ session: initialSession }) => {
setSession(initialSession);
setUser(initialSession?.user ?? null);
setLoading(false);
});
// Listen for auth changes
const { data: { subscription } } = auth.onAuthStateChange((_event, session) => {
setSession(session);
setUser(session?.user ?? null);
setLoading(false);
});
return () => {
subscription.unsubscribe();
};
}, []);
const value = {
session,
user,
loading,
signIn: async (email: string, password: string) => {
const { error } = await auth.signIn(email, password);
return { error };
},
signUp: async (email: string, password: string) => {
const { error } = await auth.signUp(email, password);
return { error };
},
signOut: async () => {
const { error } = await auth.signOut();
return { error };
},
};
return (
<AuthContext.Provider value={value}>
{!loading && children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}