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 :
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());
});
});
};