0
\$\begingroup\$

I have a function which does firebase set and update operations, but it looks messy. I want to shrink it but also make sure that it works the same. Any ideas?

  const handleUserSelect = async (user: Users) => {
    if (!currentUser) return;

    const combinedId =
      currentUser.uid > user.uid
        ? currentUser.uid + user.uid
        : user.uid + currentUser.uid;

    const currentUserChatsRef = doc(db, "userChats", currentUser.uid);
    const userChatsRef = doc(db, "userChats", user.uid);
    const chatsRef = doc(db, "chats", combinedId);

    const currentUserChats = await getDoc(currentUserChatsRef);
    const userChats = await getDoc(userChatsRef);
    const chats = await getDoc(chatsRef);

    if (!currentUserChats.exists()) {
      await setDoc(currentUserChatsRef, { chats: [] });
    }
    if (!userChats.exists()) {
      await setDoc(userChatsRef, { chats: [] });
    }
    if (!chats.exists()) {
      await setDoc(chatsRef, { messages: [] });
    }

    updateDoc(currentUserChatsRef, {
      chats: arrayUnion({
        uid: user.uid,
        name: user.name,
        avatar: user.avatar ? user.avatar : "",
      }),
    });
    updateDoc(userChatsRef, {
      chats: arrayUnion({
        uid: currentUser.uid,
        name: currentUser.displayName,
        avatar: currentUser.photoUrl ? currentUser.photoUrl : "",
      }),
    });
  };
\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.