I have the function which updates user data (currently only name). I would like to optimize its logic and particularly logic of updating participant name in chats. Currently I get entire chats collection where I find objects where the participants
array contains the current user name (who wants to update their profile) and change its previous name with a new desired name. After that I update the entire chats collection with new data (i.e updatedChats
). I need to make it work faster if possible and improve code quality.
Chats collection:
Function code:
async updateUser(data: IUser) {
const user = auth.currentUser;
if (!user) return;
// Updating user name in chats -> chat object -> participants
const q = query(collection(db, "chats"));
const querySnapshot = await getDocs(q);
const chats = querySnapshot.docs.map((doc) => doc.data() as IChat);
const updatedChats = chats.map((chat) => {
if (user.displayName && chat.participants.includes(user.displayName)) {
if (user.displayName === chat.participants[0]) {
return {
...chat,
participants: [data.name, chat.participants[1]],
};
} else {
return {
...chat,
participants: [chat.participants[0], data.name],
};
}
}
return chat;
});
await Promise.all(
updatedChats.map(async (chat) => {
const chatDocRef = doc(db, "chats", chat.chatId);
await updateDoc(chatDocRef, { participants: chat.participants });
})
);
// other logic
const userDocRef = doc(db, "users", user.uid);
await updateDoc(userDocRef, {
name: data.name,
bio: data.bio,
});
if (auth.currentUser) {
await updateProfile(auth.currentUser, {
displayName: data.name,
});
}
}