0

Below is my HTML, Client and Server JS. The issue I am having is that at first my helper function returns nothing because it takes a second for the server call to return data.

What I need is a way for the HTML to update when the data is eventually returned to the Client in the helper function.

HTML

{{#each matches}}
    {{>match}}
{{/each}}

Client JS

    Template.matches.helpers({
    matches: function() {
        Meteor.call('callAuthorize', function(error, response){
            return response.matches;
        })
    },

Server JS

Meteor.methods({

    callAuthorize: function () {
        //load Future
        Future = Npm.require('fibers/future');
        var myFuture = new Future();
        //call the function and store its result
        client.authorize(
            "FB_Auth",
            "FB_Id",
            function () {
                client.getHistory( function (error, data) {
                    myFuture.return(data);
                });
            })
        return myFuture.wait();
    }
});
}
Jim Moody
  • 758
  • 2
  • 6
  • 18
  • Make call in onRendered function for example, and response from call attach to some reactive variable which you can return in helper – sdooo Oct 09 '15 at 11:57

1 Answers1

2

You have a few options for that. You can, for example, store your method's result in a Session variable, aned return this variable instead:

if (Meteor.isClient) {
  Meteor.call('callAuthorize', function(error, response){
    Session.set('authorizeMatches') = response.matches;
  });

  Template.matches.helpers({
    matches: function() {
      return Session.get('authorizeMatches');
    }
  });
}

Or, using a reactive variable:

  Template.matches.onCreated(function() {
    this.authorizeMatches = new ReactiveVar;
    Meteor.call('callAuthorize', function(error, response){
      this.authorizeMatches.set(response.matches);
    });
  });

  Template.matches.helpers({
    matches: function() {
      return Template.instance().authorizeMatches.get();
    }
  });

You can also make use of the simple:reactive-method package:

Template.matches.helpers({
  matches: function() {
    var result = ReactiveMethod.call('callAuthorize');
    return result.matches;
  }
});

Of course, in both those options, your helper will never update by itself: only subscriptions/publications have a way of letting the client know when their data is updated, methods don't do that. You will have to use polling if you want your method to repeat that facebook API call. For example:

Meteor.setInterval(function() {
  Meteor.call('callAuthorize', function(error, response){
    Session.set('authorizeMatches') = response.matches;
  });
}, 5000); // every 5 seconds
SylvainB
  • 4,765
  • 2
  • 26
  • 39