[오늘 한 일]
- 알고리즘 3 문제 풀이
- 스탠다드반 타임어택 (todo-list redux로 구현하기)
- firebase와 연동하여 회원 가입할 때 users collection에 추가
- firebase와 연동하여 피드 업로드 할 때 feeds collection에 추가
- 헤더에 현재 로그인 한 유저의 이름 보이기
- 피드에 피드 작성자 이름 보이기
const createUserObj = async (userId) => {
try {
const docRef = await addDoc(collection(db, 'users'), {
name,
email,
avatar: null,
userId,
mbti: selectMbti()
});
console.log('Document written with ID: ', docRef.id);
} catch (e) {
console.error('Error adding document: ', e);
}
setName('');
setPassword('');
setConfirmPassword('');
setEmail('');
};
const signUp = async (event) => {
event.preventDefault();
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
const userId = userCredential.user.uid;
console.log('user', userCredential.user);
createUserObj(userId);
navigate('/');
} catch (error) {
const errorCode = error.code;
const errorMessage = error.message;
console.log('error with signUp', errorCode, errorMessage);
}
};
const createFeedObj = async (e) => {
e.preventDefault();
try {
const docRef = await addDoc(collection(db, 'feeds'), {
feedId,
title,
content,
userId,
createAt: formattedDate,
thumbImg: image,
author: user.name
});
console.log('Document written with ID: ', docRef.id);
} catch (e) {
console.error('Error adding document: ', e);
}
setTitle('');
setContent('');
navigate('/');
};
useEffect(() => {
onAuthStateChanged(auth, (user) => {
console.log('user', user); // user 정보 없으면 null 표시
setCurrentUser(user);
setUserId(user?.uid);
});
}, []);
useEffect(() => {
const fetchData = async () => {
console.log('userId', userId);
const q = query(collection(db, 'users'), where('userId', '==', userId));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data()}`);
console.log(doc.data());
setUser(doc.data());
});
};
if (userId) fetchData();
}, [userId]);
// 생략
<Btns>
{currentUser ? (
<>
<Avatar onClick={onClick} />
<span>{user?.name}</span> // 여기
</>
) : (
<>
<button onClick={() => navigate('/login')}>LOGIN</button>
<button onClick={() => navigate('/join')}>JOIN</button>
</>
)}
</Btns>
// 생략
<span>{user?.name}</span>
이 부분에 현재 로그인 한 유저의 이름을 표시하게 되는데, user에 값이 없을 때를 대비하여 옵셔널 체이닝 연산자 ?.
로 묶어주었다.
처음에 feed라는 객체를 생성할 때 userId만 담고, 유저의 이름은 담지 않았는데, userId값만 가지고 users 에 접근하여 해당하는 피드를 작성한 유저의 이름을 가져오려니까 넘 복잡하고 어려웠다.. 그래서 feed객체를 생성할 때 author라는 필드를 추가하여 피드를 작성한 사람의 이름까지 같이 담았다.
여기서 약간 애를 먹었지만 결국 했다..
return feeds.map((feed) => (
<Link to={`/feeds/${feed.feedId}`} key={feed.feedId}>
<Feed>
<AvatarAndTitle>
<Avatar />
<p>{feed.author}</p> // author 추가
<p>{feed.title}</p>
</AvatarAndTitle>
<Thumbnail src={feed.thumbImg ?? defaultThumb} alt="이미지없음" />
<time>{feed.createAt}</time>
<StDiv>댓글 수 ( ) </StDiv>
</Feed>
</Link>
));
⛰️넘고 ⛰️ 넘어......
아니 과연 산을 넘긴 했는가?