Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firebase 9 array from onSnapshot

So I need to convert data from Firebase 9 snapshot to an array.

I’ve came up with something like this, but it doesn’t return anything.

Check comments in my code.

I suppose, I should use promises, but can’t figure out the right way.

const fetchNewMessages = async (threadId: string, latestTimestamp: any) => {
  const q = query(threadRef(threadId), orderBy('timestamp', 'asc'), startAfter(latestTimestamp));
  const messages: IMessage[] = [];
  onSnapshot(q, (querySnapshot) => {
    const docs = querySnapshot.docChanges();
    docs.forEach((change) => {
      if (change.type === "added")
        messages.push(fetchDoc(change.doc));
    });
    console.log(messages.length); // here I get 34
  });
  console.log(messages.length); // here I get 0
  return messages.reverse();
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

try to wait for "onSnapshot"

  const fetchNewMessages = (threadId: string, latestTimestamp: any) => {
  const q = query(threadRef(threadId), orderBy('timestamp', 'asc'), startAfter(latestTimestamp));
  const messages: IMessage[] = [];
  return new Promise((resolve) => {
    onSnapshot(q, (querySnapshot) => {
      const docs = querySnapshot.docChanges();
      docs.forEach((change) => {
        if (change.type === "added")
          messages.push(fetchDoc(change.doc));
      });
      resolve(messages.reverse());
    });
  });
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading