Multiple access of a function in meteor while using meteor call


#1

I am trying to access the collection names posts to check if the current user has already liked or not . If liked then showing liked button in different color.
The issue is the function is called two times.

  isLiked: function() {
let self = this;
console.log();
Meteor.call('posts.isLiked', self._id, (error, result) => {
    console.log(result);
    return result;
}); 
}

The above function calls the posts.isLiked as below -

  'posts.isLiked': (_id) => {
    check(_id, String);

    if (!Meteor.user()) {
      throw new Meteor.Error(401, 'You need to be signed in to continue');
    }
    if (!_id) {
      throw new Meteor.Error(422, '_id should not be blank');
    }

  return (Posts.find( { _id: _id , already_voted: { "$in" : [Meteor.userId()]} }).count() == 1);
}

Expected -

the console to show output 1 time

Actual -

The console shows output 2 times.


#2

If you run the method from the browser console, does it still run twice? Tough to say without a bit more context. Instead of running a Meteor method to check the state of a document, maybe consider using publications with ‘field’ so that users will already have the data.

Meteor.publish("publicPostData", function (postId) {
  if(this.userId) {
    return Posts.find( { 
        _id: postId ,
        already_voted: { "$in" : [this.userId]}
    }, fields: {
        already_voted: 1,
        other_public_data: 1
    }
  }
}

});