기록
유저 이름 변경하기
als982001
2024. 8. 25. 16:39
유저 이름을 변경하는 기능을 추가하려고 한다. 유저 이름을 변경하는 것 자체는 크게 어렵지 않았다. 왜나하면 계정을 생성할 때, 계정을 업데이트하는 코드가 있었기에 이를 활용하면 되기 때문이다.
await updateProfile(credentials.user, { displayName: name });
그래서 이를 바탕으로 유저 이름을 변경하는 코드를 작성한 후, 실행해보았다.
하지만 현재 유저가 작성한 게시물에서의 유저 이름은 업데이트되지 않는다는 것을 알았다. 생각해보니 게시물(tweet)의 유저 이름은 username이라는 key-value 쌍으로 별도로 저장되어 있다는 걸 떠올렸다. 그래서 모든 tweet의 username을 변경하는 과정이 추가해야 한다.
const handleChangeName = async () => {
if (isLoading || !user) {
return;
}
try {
setIsLoading(true);
await updateProfile(user, { displayName: updatedName });
const tweetUpdatePromises = tweets.map((tweet) => {
const tweetDocRef = doc(db, "tweets", tweet.id);
return updateDoc(tweetDocRef, { username: updatedName });
});
await Promise.all(tweetUpdatePromises);
} catch (e) {
console.error(e);
} finally {
setIsLoading(false);
setUpdate(false);
setUpdatedName("");
}
};
tweet을 update하는 함수인 updateDoc은 Promise를 반환한다. 그렇기에 모든 tweet에 대한 updateDoc의 Promise를 저장하는 배열을 생성한 후, Promise.all을 통해 처리하였다.
const fetchTweets = async () => {
if (isNull(user)) {
return;
}
const tweetQuery = query(
collection(db, "tweets"),
where("userId", "==", user.uid),
// orderBy("createdAt", "desc"),
limit(25)
);
const snapshot = await getDocs(tweetQuery);
const tweets: ITweet[] = snapshot.docs.map((doc) => {
const { tweet, createdAt, userId, username, photo } = doc.data();
return { tweet, createdAt, userId, username, photo, id: doc.id };
});
setTweets(tweets);
};
useEffect(() => {
fetchTweets();
}, [user?.displayName]);
그리고 tweets을 fetch하는 useEffect문의 의존성 배열에 user의 displayName을 추가하였다. 이를 통해 user의 displayName이 변경될 때마다 새로 tweets를 fetch해와서 변경된 이름이 보이게 된다.