Vuejs & Firestore - How to Update when Data Changes in Firestore

I've gone through a bunch of tutorials and docs but cannot seem to be able to update on page when data changes in Firestore (NOTE: not Firebase)

Heres what I have currently which is working fine except if data changes in the DB it is not reflected on the page itself unless I refresh. Code below is within script tags:

 import { recipeRef } from '../../firebase';
 export default {
 data() {
  return {
    recipes: []
  }
},
firestore: {
  recipes: recipeRef
},
created() {
  db.collection('recipes').get().then((onSnapshot) => {
    this.loading = false
    onSnapshot.forEach((doc) => {
      let data = {
        'id': doc.id,
        'name': doc.data().name
      }
      this.recipes.push(data)
    })

  })
}

I'm not using Vuex. Adding data, editing and reading works fine. Just not reflecting changes once data has changed. Maybe there is a life cycle hook Im supposed to be using? For "onSnapshot" - Ive tried "snap", "querySnapshot" etc. No luck.

Thanks in advance.

1 answer

  • answered 2018-03-13 21:50 whusterj

    I am not familiar with the firestore API, but glancing through the docs, it looks like calling get() is how you query a single time. Where you have onSnapshot should really be querySnapshot -- that is, the results of a one query. See:

    versus:

    So to get live updates, it looks like you need to create a listener, like so:

    db.collection('recipes')
        .onSnapshot(function(snapshot) {
            snapshot.forEach(function(doc) {
                // Find existing recipe in this.recipes
                // and swap in the new data
            });
        }, function(error) {
            // handle errors
        });
    

    I think you will need to add that listener in addition to the get() query you are currently doing. Hope this helps!