diff --git a/src/common/UserContext.tsx b/src/common/UserContext.tsx new file mode 100644 index 00000000..a9456602 --- /dev/null +++ b/src/common/UserContext.tsx @@ -0,0 +1,63 @@ +import { createContext, useContext, useState, useEffect, PropsWithChildren } from 'react'; +import { auth } from './config'; +import { onAuthStateChanged } from 'firebase/auth'; + +// 사용자 정보의 타입 정의 +interface User { + name: string; + uid: string; + email: string; + photoUrl: string; + phone: string; + emailVerified: boolean; +} + +// 컨텍스트의 타입 정의 +interface UserContextType { + user: User | null; + updateUser: (newUser: User | null) => void; // 사용자 정보 업데이트 함수 추가 +} + +// 초기 컨텍스트 값 +const initialContext: UserContextType = { + user: null, + updateUser: () => {}, // 빈 함수 초기화 +}; + +const UserContext = createContext(initialContext); + +export function useUser() { + return useContext(UserContext); +} + +export function UserProvider({ children }: PropsWithChildren) { + const [user, setUser] = useState(null); + + useEffect(() => { + const unsubscribe = onAuthStateChanged(auth, (authUser) => { + if (authUser) { + // Firebase 사용자 정보를 사용자 타입으로 변환 + const user: User = { + name: authUser.displayName || '', + uid: authUser.uid, + email: authUser.email || '', + photoUrl: authUser.photoURL || '', + phone: authUser.phoneNumber || '', + emailVerified: authUser.emailVerified, + }; + console.log(user); + setUser(user); + } else { + setUser(null); + } + }); + + return () => unsubscribe(); + }, []); + + const updateUser = (newUser: User | null) => { + setUser(newUser); + }; + + return {children}; +}