简体   繁体   中英

The length of array is showing zero

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?

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);
}```

The Firebase code running asynchronously. Try to maybe log the list in the callback function or something like that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM