내일배움캠프 최종 프로젝트 - 프로필 페이지(1)

새벽로즈·2024년 1월 19일

1. 유저 프로필 불러오기

useEffect(() => {
  const unsubscribe = onAuthStateChanged(auth, async user => {
    if (user) {
      const userDocRef = doc(db, 'users', user.uid);
      const userDocSnap = await getDoc(userDocRef);

      if (userDocSnap.exists()) {
        const userData = userDocSnap.data();
        setUserProfile({
          email: user.email,
          nickName: userData.nickname,
          birthDate: userData.birthdate,
          photoURL: userData.photoURL,
          sexType: userData.sexType,
        });
      }
    } else {
      setUserProfile(null);
    }
  });
  return () => unsubscribe();
}, []);
  • 'useEffect'를 사용하여 컴포넌트가 마운트될 때, Firebase Authentication에서 현재 로그인한 사용자의 상태 감지
  • 로그인한 사용자가 있을 경우, Firestore의 'users' 컬렉션에서 해당 사용자의 문서 조회
  • 문서가 존재하면, 해당 데이터를 'setUserProfile'를 통해 상태 저장

2. 닉네임 변경 기능

//편집 모드 전환
const clickNickNameEditModeHandler = () => {
  setIsNickNameEditing(!isNickNameEditing);
  setNewNickName(userProfile?.nickName || '');
};

//닉네임 저장
const clickNickNameSaveHandler = async () => {
  if (auth.currentUser) {
    await updateDoc(doc(db, 'users', auth.currentUser.uid), {
      nickname: newNickName,
    });
    setUserProfile(prev => ({ ...prev, nickName: newNickName }));
    setIsNickNameEditing(false);
  }
};
  • 사용자가 닉네임 편집 모드로 전환할 수 있는 버튼 제공
  • 편집 모드에서는 사용자가 새 닉네임을 입력할 수 있고 '저장' 버튼으로 Firestore에 업데이트할 수 있음

3. 성별 설정 기능 (최초 한 번만)

const clickSaveSexTypeHandler = async () => {
  if (auth.currentUser && userProfile) {
    await updateDoc(doc(db, 'users', auth.currentUser.uid), {
      sexType: sexType,
    });
    setUserProfile({ ...userProfile, sexType: sexType });
  }
};
  • 사용자의 성별이 미설정 상태('--미설정--')일 경우에만 성별을 설정할 수 있는 드롭다운 메뉴가 표시됨
  • 사용자가 성별을 선택하고 저장 버튼을 클릭하면 Firestore에 해당 정보가 업데이트됨

4. 생년월일 추가 기능 (최초 한 번만)

const clickSaveBirthDateHandler = async () => {
  if (auth.currentUser && newBirthDate) {
    await updateDoc(doc(db, 'users', auth.currentUser.uid), {
      birthdate: newBirthDate,
    });
    setUserProfile({ ...userProfile, birthDate: newBirthDate });
  }
};
  • 사용자의 생년월일이 빈 문자열('')일 경우에만 생년월일을 추가할 수 있는 입력 필드가 표시됨
  • 사용자가 날짜를 입력하고 저장 버튼을 클릭하면 Firestore에 해당 정보가 업데이트됨

5. 기본 프로필 이미지 출력 및 변경 기능

const clickProfileImageHandler = async (event: React.ChangeEvent<HTMLInputElement>) => {
  const file = event.target.files?.[0];
  if (!file || !auth.currentUser) return;

  const storageRef = ref(storage, `ProfilePic/${auth.currentUser.uid}`);
  await uploadBytes(storageRef, file);
  const photoURL = await getDownloadURL(storageRef);

  await updateDoc(doc(db, 'users', auth.currentUser.uid), {photoURL});
  setUserProfile(prev => ({ ...prev, photoURL: photoURL }));
};
  • 사용자가 프로필 이미지를 업로드할 수 있는 입력 필드가 제공됨
  • 이미지를 선택하고 업로드하면 Firebase Storage에 저장되고, Firestore에 해당 이미지의 URL이 업데이트됨
  • 저장된 이미지 URL이 있을 경우 프로필 이미지로 표시됨

오늘의 한줄평 : 새록새록 지난번 과제하던것도 프로젝트 하던 것도 생각이 났었다. 건강상태가 안좋은 요즘, 그래도 열심히 하자.

profile
귀여운 걸 좋아하고 흥미가 있으면 불타오릅니다💙 최근엔 코딩이 흥미가 많아요🥰

0개의 댓글