Reputation: 5217
I am using the new Firebase Web SDK v9 (beta 8) with NuxtJS2. I have a child component that allows a user to edit his post data. This updates a document in Firestsore with the new post changes. However, my question is...how do I get have my parent component get realtime updates of this new data?
Let me explain:
I have the following example components structure in the app:
<PostCardDetail>
<PostEdit />
</PostCardDetail>
PostCardDetail.vue
script section where I am doing the data fetch:
import { doc, getDoc } from 'firebase/firestore'
import { mapGetters } from 'vuex'
import { db } from '~/plugins/firebase'
export default {
name: 'PostCardDetail',
data() {
return {
post: {}
}
},
async fetch() {
const docRef = doc(db, 'posts', this.$route.params.postId)
const docSnap = await getDoc(docRef)
this.post = docSnap.data()
},
mounted () {
// I believe I will need to mount the realtime listener here?
},
}
</script>
The PostEdit.vue
script section where I am doing the data editing:
editPost() {
const postRef = doc(db, 'posts', this.post.id)
await updateDoc(postRef, {
...editedPost,
updatedAt: serverTimestamp()
})
console.log('updated!')
this.$store.dispatch('edit', false)
alert('Post successfully updated!')
}
I am able to successfully edit the data, but to view the latest changes, I need to manually refresh the browser. How can I get automatic real time update with firestore after post is edited by user? I assume this listener will be in the mounted() hook property of PostCardDetail
?
My attempt:
mounted() {
// eslint-disable-next-line no-unused-vars
const unsub = onSnapshot(
doc(db, 'posts', this.$route.params.postId),
(snapshot) => {
this.post = snapshot.data()
}
)
}
This SEEMS to work OK, but feels a bit clunky. Is this the recommended way to approach this with NuxtJS?
Upvotes: 3
Views: 495
Reputation: 50830
The query looks perfectly fine and similar to as mentioned in the documentation.
I assume this listener will be in the mounted() hook property of PostCardDetail
Ideally you might want to set the listener once the component is created and I've mostly seen listeners being set in created()
created() {
const unsub = onSnapshot(
doc(db, 'posts', this.$route.params.postId),
(snapshot) => {
this.post = snapshot.data()
}
)
}
To use the unsub
somewhere else, you can set it in the data property or pass it to other components depending on your use case.
Upvotes: 1