Hi , is there a way to use observeChanges
method on the client while using the vue-meteor package? If yes, where and how to use it to work properly?
Thank you!
Hi , is there a way to use observeChanges
method on the client while using the vue-meteor package? If yes, where and how to use it to work properly?
Thank you!
Thereโs nothing stopping you putting (e.g.) Meteor.users.find(query).observeChanges({...})
anywhere you want. vue-meteor
doesnโt prevent you from doing that.
Why do you want to do it though, and what do you want to do with changes?
vue-meteor-tracker
provides an easier way to create reactive properties based on mongo queries, e.g.:
// UserList.vue
<template>
<div class="users">
<div v-for="user in users" :key="user._id" class="user">
<img :src="user.profile.avatarImg"/>
<span>{{user.profile.name}}</span>
</div>
</div>
</template>
<script>
export default {
props: ['teamId'],
$subscribe: { // this is provided by vue-meteor-tracker
usersInTeam: [this.teamId], // this subscription will automatically cancel when the component is destroyed
},
meteor: { // this is provided by vue-meteor-tracker
users() {
// this will auomatically observe changes and update the users prop.
return Meteor.users.find({teamId: this.teamId}, {fields: {profile: 1}, sort: {profile.name: 1}});
}
},
}
</script>
Thank you for your answer. I need to watch for changes to notify user that new document was added (push notification). I donโt want to only render data.
Where to put Meteor.users.find(query).observeChanges({...})
best? In mounted()
method?
Yes, put it in the mounted()
method. You would need to store the observer handle which is returned so that you can stop()
the observer when the component is destroyed or the user logs out or whatever.
Could you send me an example how I can do this?
Off the top of my head (untested):
export default {
mounted() {
this.$autorun(() => {
// put this in an autorun in case Meteor.userId() changes
this.observerHandle = notificationsCollection.find({
userId: Meteor.userId()
}).observeChanges({
added: (notificationId, fields) => {
// notify user...
})
});
},
beforeDestroy() {
// cancel the observer if we navigate away from this component?
this.observerHandle && this.observerHandle.stop();
},
}
OK, now I see that observeChanges
method returns the handle. Thank you, you helped me a lot!