53 lines
1.1 KiB
TypeScript
53 lines
1.1 KiB
TypeScript
import {
|
|
createContext,
|
|
useContext,
|
|
useEffect,
|
|
useMemo,
|
|
useState,
|
|
type PropsWithChildren,
|
|
} from 'react';
|
|
import { onAuthStateChanged, type User } from 'firebase/auth';
|
|
|
|
import { auth } from '@/lib/firebase';
|
|
|
|
type AuthContextValue = {
|
|
user: User | null;
|
|
initializing: boolean;
|
|
};
|
|
|
|
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
|
|
|
export function AuthProvider({ children }: PropsWithChildren) {
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [initializing, setInitializing] = useState(true);
|
|
|
|
useEffect(() => {
|
|
const unsubscribe = onAuthStateChanged(auth, (nextUser) => {
|
|
setUser(nextUser);
|
|
setInitializing(false);
|
|
});
|
|
|
|
return unsubscribe;
|
|
}, []);
|
|
|
|
const value = useMemo(
|
|
() => ({
|
|
user,
|
|
initializing,
|
|
}),
|
|
[initializing, user]
|
|
);
|
|
|
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
|
}
|
|
|
|
export function useAuth() {
|
|
const context = useContext(AuthContext);
|
|
|
|
if (!context) {
|
|
throw new Error('useAuth must be used within an AuthProvider');
|
|
}
|
|
|
|
return context;
|
|
}
|