0

Hi I'm using Javascript method to load message from FCM and creating array to pass an other method in other file but its not working, console log showing all records but array is undefined.

window.loadMessages = function(newthread = '') {

  var chatthread = newthread;
  var chat_messages_arr = [];
  const recentMessagesQuery = query(collection(getFirestore(), chatthread), orderBy('timestamp', 'asc'), limit(12));

  onSnapshot(recentMessagesQuery, function(snapshot) {
    //   console.log(snapshot);
    var countercht = 0;
    snapshot.docChanges().forEach(function(change) {
      if (change.type === 'removed') {
        // deleteMessage(change.doc.id);
      } else {
        //   console.log(change.doc.data());
        var message = change.doc.data();
        var cahtArr = [];
        cahtArr = {
          id: change.doc.id,
          name: message.name,
          message: message.text,
          timestamp: message.timestamp
        };
        chat_messages_arr.push(cahtArr);
        countercht++;
      }
    });



  });

  return chat_messages_arr;
};

and in the other file I'm calling this method


function loadMessageses(chat_thread) {
    var loadmessages = new loadMessagess(chat_thread);
    console.log(loadmessages);

}

I want to know how to return values from JavaSript method.

phuzi
  • 12,078
  • 3
  • 26
  • 50
DevOops
  • 11
  • 2
  • Probably the "usual" problem with not handling the asynchronous nature of the API call(?) correctly, I suppose? https://stackoverflow.com/q/14220321/1427878 – CBroe Nov 03 '22 at 09:38
  • After formatting the code in a reasonable manner, it becomes a little easier to see what's going on... Your messages aren't being loaded until the callback to `onSnapShot` is called, given the name of the function I would not expect it to be called until some other event in the future has happened and a `snapshot` event of some kind is triggered. Can you confirm? – phuzi Nov 03 '22 at 09:51
  • i am new in javascript , i dint get your point can you please edit my question with correct format – DevOops Nov 03 '22 at 11:13

0 Answers0