Skip to content

Commit

Permalink
Merge pull request #6 from JSH99/feat/userinfo
Browse files Browse the repository at this point in the history
유저 정보 연결 컨텍스트를 작성한다.
  • Loading branch information
minseokiim authored Sep 14, 2023
2 parents df01a5e + 78de5e5 commit 06fc278
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions src/common/UserContext.tsx
Original file line number Diff line number Diff line change
@@ -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<UserContextType>(initialContext);

export function useUser() {
return useContext(UserContext);
}

export function UserProvider({ children }: PropsWithChildren) {
const [user, setUser] = useState<User | null>(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 <UserContext.Provider value={{ user, updateUser }}>{children}</UserContext.Provider>;
}

0 comments on commit 06fc278

Please sign in to comment.