I am following a simple tutorial on Firebase 9. Everything worked fine until I tried to use onSnapshot method to get the snapshot of changes in db every time the cahnge occurs. But onSnapshot is not working. I mean it work only for the initial fetch of data, but does not execute the callback function when the change occurs. I am following a tutorial so my code is identical to the code from the tutorial. My question is whether there is something I need to do in the console to rectify this, some kind of rules or permissions or something.
My code:
const colRef = collection(db, 'books');
const q = query(colRef, where('author', '==', 'patrick rothfuss'));
onSnapshot(q, (snapshot) => {
let books = []
snapshot.docs.forEach(doc => {
books.push({ ...doc.data(), id: doc.id })
})
console.log(books)
})
You can use snapshot.docChanges().forEach method to read and detect changes in data on real time.
I recommend you use this method to modify the array when a change occur.
You can view the code here: https://github.com/firebase/snippets-web/blob/1c4c6834f310bf53a98b3fa3c2e2191396cacd69/snippets/firestore-next/test-firestore/listen_diffs.js#L8-L23