Reputation: 61
I am trying to return the correct count of messages (length of listMessage
) from the function below. I can retrieve correct message Objects into listMessage
, but its length is always zero.
checkLastMsg = () =>
{
var groupChatId = null;
var listMessage = [];
// console.log(this.peerUserId);
if (this.hashString(this.currentUserId) <= this.peerUserId)
{
groupChatId = `${this.currentUserId}-${this.peerUserId}`;
}
else
{
groupChatId = `${this.peerUserId}-${this.currentUserId}`;
}
// console.log(groupChatId);
myFirestore
.collection(AppString.NODE_MESSAGES)
.doc(groupChatId)
.collection(groupChatId)
.onSnapshot(
snapshot =>
{
snapshot.docChanges().forEach(change =>
{
if (change.type === AppString.DOC_ADDED)
{
listMessage.push(change.doc.data())
}
})
},
err =>
{
this.props.showToast(0, err.toString())
})
// console.log(listMessage.length);
console.log(listMessage.length);
}
Could anyone check if something is wrong here and how I can fix this issue?
Upvotes: 0
Views: 121
Reputation: 121
Like everybody said, the code is asynchronous, hence you can make work like this:
checkLastMsg = async () =>
{
var groupChatId = null;
var listMessage = [];
// console.log(this.peerUserId);
if (this.hashString(this.currentUserId) <= this.peerUserId)
{
groupChatId = `${this.currentUserId}-${this.peerUserId}`;
}
else
{
groupChatId = `${this.peerUserId}-${this.currentUserId}`;
}
// console.log(groupChatId);
await myFirestore
.collection(AppString.NODE_MESSAGES)
.doc(groupChatId)
.collection(groupChatId)
.onSnapshot(
snapshot =>
{
snapshot.docChanges().forEach(change => {
if (change.type === AppString.DOC_ADDED) {
listMessage.push(change.doc.data())
}
})
},
err => {
this.props.showToast(0, err.toString())
}
)
// console.log(listMessage.length);
console.log(listMessage.length);
}```
Upvotes: 1
Reputation: 388
The Firebase code running asynchronously. Try to maybe log the list in the callback function or something like that
Upvotes: 0