I am using Firebase for Authentication and a database within a Vue app. The component I am working on listens for changes within a 'friends' collection for a specific user.
I would simply like to display the list of friends while reflecting changes from the database in real-time.
So far, I have taken two approaches and both result in the same problem of successfully capturing the changes, but being unable to display the change within the dom.
Approach 1
Within the created() function I add my listener using the .onSnapshot()
function. This successfully captures the changes in the database. However, if I set this.friends
to the updated values the screen does not change.
Approach 2
Using Vuex to load the friends list. I created a watch function for the store which successfully tracks the changes. But changing the this.friends
within this watch function is also not updating the screen.
Reactivity for simpler variables is working as expected.
<template>
<v-container fluid>
{{ friends }}
</v-container>
</template>
<script>
import db from '@/firebase/firestore'
import firebase from 'firebase'
export default {
name: 'Test',
data() {
return {
friends: []
}
},
created() {
let firebaseUser = firebase.auth().currentUser
let ref = db.collection('users')
ref.where('user_id', '==', firebaseUser.uid).limit(1).get()
.then( snapshot => {
if (snapshot.docs[0].data()) {
db.collection("users").doc(snapshot.docs[0].id)
.onSnapshot(function(doc) {
let user = doc.data()
console.log('friends', user.friends) // outputs correctly
this.friends = user.friends // does not update dom
})
}
})
},
}
</script>