javascript - 如何(使用 React JS Web)和 Firestore,您能否找出聊天室(在 Firestore 数据库上)何时收到新消息?

标签 javascript reactjs google-cloud-firestore

我正在尝试使用 FireStore 和 React JS (Web) 构建一个应用程序

我的Firestore数据库基本上有:

  • ChatRoom 的集合ChatRooms
  • 每个聊天室都有许多消息,这是一个子集合,例如:

this.db.collection("ChatRooms").doc(电话号码-此处).collection("messages")

此外,每个聊天室都有一些客户信息,例如名字、姓氏等,其中一个非常重要:

lastVisited 这是一个时间戳(或时间戳)

我想我应该放置一个 React Hook,它每秒都会更新 lastVisited 字段,这意味着尝试在 Firestore 上尽可能准确地记录我上次离开聊天室的时间。

基于此,我想检索上次访问后进入的每个客户(聊天室)的所有消息

=> lastVisited 字段。 :)

并显示通知。

我尝试过使用 messages 子集合上的 .onSnapshot 监听器以及 Firestore Transactions 的组合,但我并不幸运。我的应用程序有问题,它一直显示两个,然后一个,然后什么也没有,回到两个,依此类推,我很痛苦。

这是我的代码!

请感谢您的帮助!!!

unread_messages = currentUser => {
    const chatRoomsQuery = this.db.collection("ChatRooms");
    // const messagesQuery = this.db.collection("ChatRooms");

    return chatRoomsQuery.get().then(snapshot => {
      return snapshot.forEach(chatRoom => {
        const mess = chatRoomsQuery
          .doc(chatRoom.id)
          .collection("messages")
          .where("from", "==", chatRoom.id)
          .orderBy("firestamp", "desc")
          .limit(5);
        // the limit of the messages could change to 10 on production
        return mess.onSnapshot(snapshot => {
          console.log("snapshot SIZE: ", snapshot.size);
          return snapshot.forEach(message => {
            // console.log(message.data());
            const chatRef = this.db
              .collection("ChatRooms")
              .doc(message.data().from);

            // run transaction
            return this.db
              .runTransaction(transaction => {
                return transaction.get(chatRef).then(doc => {
                  // console.log("currentUser: ", currentUser);
                  // console.log("doc: ", doc.data());
                  if (!doc.exists) return;

                  if (
                    currentUser !== null &&
                    message.data().from === currentUser.phone
                  ) {
                    // the update it
                    transaction.update(chatRef, {
                      unread_messages: []
                    });
                  }
                  // else
                  else if (
                    new Date(message.data().timestamp).getTime() >
                    new Date(doc.data().lastVisited).getTime()
                  ) {
                    console.log("THIS IS/ARE THE ONES:", message.data());
                    // newMessages.push(message.data().customer_response);

                    // the update it
                    transaction.update(chatRef, {
                      unread_messages: Array.from(
                        new Set([
                          ...doc.data().unread_messages,
                          message.data().customer_response
                        ])
                      )
                    });
                  }
                });
              })
              .then(function() {
                console.log("Transaction successfully committed!");
              })
              .catch(function(error) {
                console.log("Transaction failed: ", error);
              });
          });
        });
      });
    });
  };

最佳答案

搜索一下,似乎实现这种比较的最佳选择是使用方法toMillis()以毫秒为单位转换时间戳。这样,您应该能够更好、更轻松地比较结果 - 有关该方法的更多信息可以在官方文档 here 中找到。 - 最后一条消息和最后一次访问的时间戳

我相信这将是您的最佳选择,正如社区帖子 here 中提到的那样,这将是在 Firestore 上比较时间戳的唯一解决方案 - 有一个名为 isEqual() 的方法,但它对您的用例没有意义。

我建议您尝试使用它来比较您的应用程序的时间戳。除此之外,社区还有另一个问题 - 可在此处访问:How to compare firebase timestamps? - 如果用户具有与您类似的用例和目的,我相信这也可能对您有一些想法和想法有所帮助。

如果这些信息对您有帮助,请告诉我!

关于javascript - 如何(使用 React JS Web)和 Firestore,您能否找出聊天室(在 Firestore 数据库上)何时收到新消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60860835/

相关文章:

javascript - 数据表不允许将多个页脚行包含到导出的 pdf 文件中

node.js - X-Content-Encoding-Over-Network 位于响应 header 中,但不位于 Content-Encoding 中

javascript - 如何在 React 中动态更改按钮大小和颜色

firebase - Firestore (4.10.1) : Could not reach Firestore backend. Cloud Functions 中的 Firestore 访问问题

ios - Firebase 的 putData (存储)和 setData (数据库)是否会不断尝试直到成功/失败?

javascript - 在 JavaScript 中,如何以简单的方式检查 "a"与 "b," "c,"等?

javascript - 合并 js 文件时 Typescript Intellisense 不起作用

javascript - 如何在显示主要内容之前抓取运行 Javascript 且带有 cookie 检查的网页

javascript - 如何使用 ReactJS 从多个 URL 获取数据?

javascript - 如何获取 firestore 文档中的字段?