0

I have a client that have this helper:

Template.eventTemplate.helpers({
    returnUsersEvents: function(){
        Meteor.call("events.getByUserId", function(error, result){
        if(error){
            console.log("error" + error.reason);
            return;
        }
        console.log(result);
        return result; 
        });

    }
});

The method on collection

Meteor.methods({
  'events.insert'(Event) {
    Events.insert(Event);
  },
  'events.getByUserId'(){
    var events =  Events.find({UserId: Meteor.userId()}).fetch();
    console.log(events);
    return events;
  }
})

I have one object in my collection. But I retrieve three objects of the same type. Can anyone tell me what I am doing wrong?

Here is my template

<ul class="demo-list-item mdl-list">
    {{#each returnUsersEvents}}
    <li class="mdl-list__item">
        <span class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect">
            <i class="material-icons mdl-list__item-icon">map</i>
            <a class="" href="/event/{{_id}}">{{EventName}}</a>
        </span>
    </li>
    {{/each}}
</ul>
K N
  • 279
  • 5
  • 22

1 Answers1

3

Your problem is that your returnUsersEvents() helper is not returning anything at all. You have a return statement inside the callback of the Meteor.call(). This will not become the return value of the .call() itself.

Meteor.call() is asynchronous, which means that the .call() will return before the result is available inside the callback. To make this work, you need the helper to return the result from the callback when it arrives, which is at some point in time after the helper has returned the first time.

The typical pattern in Meteor to achieve this is to use a ReactiveVar that the helper is tracking on, and to set that ReactiveVar from inside the callback.

Here is a SO answer which shows how to do that.

And on the server: You need the fetch. Otherwise you are returning a database cursor, which is not a serializeable object (which means it can't be returned over DDP, the protocol that the Meteor server sends the result to the client over)

Community
  • 1
  • 1
Jesper We
  • 5,977
  • 2
  • 26
  • 40