I am trying to pass the result of the queried documents (which is an array) outside of the function. However, accessing this array outside of the onSnapshot function yields undefined.
I have spent a whole day on this trying various things but can't figure it out.
export const getComments = (taskId) => {
const comments = [] // i want to return this array once it is filled wit documents
const dbRef = db.collection('tasks').doc(taskId).collection('comments') // comments is a subcollection of each task document
dbRef.onSnapshot(
(querySnapshot) => {
querySnapshot.forEach((doc) => {
comments.push(doc.data()) //each doc.data() is an object that gets pushed to the comments array. Lets say that the 1st doc.data() is {userId: 'xyz', user: 'Kiu', comment: 'this is my 1st stack overflow question'}
})
console.log('value for comments[0] inside onSnapshot')
console.log(comments[0]) //sucessfully display the 1st object in the array as {userId: 'xyz', user: 'Kiu', comment: 'this is my 1st stack overflow question'}
},
(error) => {
throw new Error(error.message)
}
)
console.log('value for comments[0] outside onSnapshot')
console.log(comments[0]) // this is undefined for some reason????
console.log('value for the whole comments array outside onSnapshot')
console.log(comments) // this does actually show the whole array, however any method used here (i.e. forEach(), map() ) returns undefined. ????
return comments
}
When calling getComments(taskId) in App.js the console.log() result is not what I expect. Can somebody please help this newbie?
--update#1 : I read elsewhere on stack overflow that onSnapshot is to activate a listener. Listeners are not to be used in an asynchronous fashion , as listeners stay 'on' until unsubscribed. So i don't think using async and await will work for this one. I think this is where I read it. See the bottom of this discussion: What is the right way to cancel all async/await tasks within an useEffect hook to prevent memory leaks in react?