Utilizing Firebase for Authentication and integrating a database into a Vue app, my current task involves monitoring changes within a 'friends' collection specific to a user.
The objective is to seamlessly display the list of friends while reflecting real-time updates from the database.
I've experimented with two different approaches, both successful in capturing the changes but encountering an issue when it comes to updating the DOM.
Strategy 1
Incorporating the .onSnapshot()
function within the created() method, I can effectively capture database modifications. However, setting this.friends
to the updated values does not result in a visual change on the screen.
Strategy 2
Implementing Vuex to load the friends list, I established a watch function for the store, which adeptly tracks changes. Despite this, altering this.friends
inside the watch function also fails to update the displayed content.
Reactivity works as expected for simpler variables.
<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>