Template helpers are being called twice every time. Why?

So I was playing around with my code and my helpers are being called twice every time I navigate to a page that has it.

Template.note.onRendered(function() {
  var template = this;
    readingTimeTarget: template.$('#reading-time'),

Template.note.onCreated(function() {
  var self = this;
  self.autorun(function() {
    self.subscribe('notes', FlowRouter.getParam('teamSlug'));    

// These are called twice.
  note: function() {
    console.log("Yep it's being called.");
    var noteSlug = FlowRouter.getParam('noteSlug');
    var note = Notes.findOne({"noteSlug": noteSlug});
    return note;
  createdAt: function() {
    var noteSlug = FlowRouter.getParam('noteSlug');
    var note = Notes.findOne({"noteSlug": noteSlug});
    if (typeof note !== "undefined") {
      var createdAtMoment = moment(note.createdAt);
      return createdAtMoment.fromNow();

The code in onCreated is called once as expected, but helpers are called twice.

Any ideas why this is happening? I would love some deep understanding on how Blaze helpers are called and when they are triggered. Thank you!

This: FlowRouter.getParam(‘noteSlug’) is a reactive variable. So do a console.log(FlowRouter.getParam(‘noteSlug’))

I suspect you will see it multiple times. Every time is changes this helper will recalculate.

A helper is a Tracker() which you can lookup in the docs to see how reactivity exactly works. A helper is reactive by default.

Ok that makes sense, but shouldn’t that reactivity only ‘react’ when the URL changes? When I visit the note page, the console fires off twice. Shouldn’t it only fire once since I only visited a URL this one time?

Thanks so much for your insight, I appreciate it.


I guess:

1 First the template loads.
-> first log (so this is not because of reactivity, just the template gets rendered)

2 Then the subscription becomes ready
-> second log (this is reactive on the find() call)

3 If you would change the url
-> third log (reactive on flow router)

In general it’s not an issue that some things are rendered multiple times, I would not worry too much about it. Also because you should not do heavy tasks in helpers anyway so it would just be updating a simple var. Nothing to worry about.

Finding out why it’s doing it can be tricky because reactivity is not instantly visible in the code. You need to know which things are reactive and which are not.

@lucfanken - You say that you should not do heavy tasks in helpers. This sounds completely logical, but as a meteor newb, where should the heavy tasks be offloaded to? I’m having the same issue as @sergiotapia but I have some heavy tasks and this multiple-time processing latency is compounding quickly.

Maybe open a new topic and define which tasks you need to execute and add some code examples with it?

Probably right, didn’t mean to hijack