flimflam57
flimflam57

Reputation: 1334

ReactiveVar not getting new value on Tracker.autorun in Meteor

I'm instantiating a new ReactiveVar:

Template.myTemplate.onCreated(function() {
   this.var1 = new ReactiveVar(0);
}

I'm having a Tracker.autorun force a rerun when the user selects a new year value:

Template.myTemplate.onRendered(function() {
  Tracker.autorun(function() {
  var year = Session.get('chartYear').toString(); // This session is from another template
  // Do stuff 
  ...
  Template.instance().var1.set(new data);
  }
}

My helpers to rerun the function:

Template.myTemplate.helpers({
  function1: function () {
    return Template.instance().var1.get();
}

Not sure what's going on but when a year value is selected on first go, everything runs fine. But when the user selects a new year value, a TypeError results:

"TypeError: null is not an object (evaluating 'Template.instance().var1')"

However, if I replace the ReactiveVars with Sessions instead, everything works fine when the user selects different year values. Could anyone help out?

Upvotes: 0

Views: 589

Answers (1)

JeremyK
JeremyK

Reputation: 3240

It's not clear which line is throwing that error (if the following doesn't apply post the full error indicating if this is from the helper or onRendered event, etc).

However I suspect this is from the Template.onRendered event, which requires you to access the template instance from the this object, like you are in your Template.onCreated event.

So try changing your onRendered function to this:

Template.myTemplate.onRendered(function() {
  templateInstance = this;
  Tracker.autorun(function() {
    var year = Session.get('chartYear').toString(); // This session is from another template
    // Do stuff 
    ...
    templateInstance.var1.set(newData);
  }
}

Upvotes: 1

Related Questions