import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { auth } from './firebase';
interface AuthContextProps {
currentUser: firebase.User | null;
signup: (email: string, password: string) => Promise<firebase.auth.UserCredential>;
login: (email: string, password: string) => Promise<firebase.auth.UserCredential>;
logout: () => Promise<void>;
}
const AuthContext = createContext<AuthContextProps | undefined>(undefined);
interface AuthProviderProps {
children: ReactNode;
}
export function useAuth(): AuthContextProps {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
export function AuthProvider({ children }: AuthProviderProps): JSX.Element {
const [currentUser, setCurrentUser] = useState<firebase.User | null>(null);
const [loading, setLoading] = useState(true);
const handleAuthStateChanged = (user: firebase.User | null): void => {
setCurrentUser(user);
setLoading(false);
};
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(handleAuthStateChanged);
return () => {
unsubscribe();
};
}, []);
const value: AuthContextProps = {
currentUser,
signup: async (email, password) => auth.createUserWithEmailAndPassword(email, password),
login: async (email, password) => auth.signInWithEmailAndPassword(email, password),
logout: async () => auth.signOut(),
};
return <AuthContext.Provider value={value}>{!loading && children}</AuthContext.Provider>;
}