gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:59:03 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com