Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 752
Yesthe Cia Avatar asked Mar 13 '18 21:03

Yesthe Cia


1 Answers

Remove the get() and just replace with snapshot - like so

created() {
  db.collection('recipes').onSnapshot(snap => {
      let foo = [];
      snap.forEach(doc => {
       foo.push({id: doc.id, name: doc.data().name})

       });
    }
});
like image 61
matshidis Avatar answered Sep 28 '22 01:09

matshidis