Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor ReactiveVar - TypeError: Cannot call method 'set' of undefined

I tried to use ReactiveVar. I doesnt know how to handle ReactiveVar. Here the code I have tried.

Template.Home.helpers({
  names: function(){
    temp = Template.instance().name.get();
    return temp;
  }
});

Template.Home.onCreated(function () {
  this.name = new ReactiveVar();
  Meteor.call("getNames", function(error, result) {
    if(error){
      alert("Oops!!! Something went wrong!");
      return;
    } else {
      this.name.set(result); // TypeError: Cannot call method 'set' of undefined
      return;
    }
  });
});

Is am I right to set and get ReactiveVar? or How to set and get the ReactiveVar ??

like image 637
Ramesh Murugesan Avatar asked Feb 11 '23 05:02

Ramesh Murugesan


1 Answers

Your logic is correct, your error is actually a common JS pitfall : inside the Meteor.call callback function, this scope is modified and no longer references the template instance.

You need to use Function.prototype.bind and update your code :

Template.Home.onCreated(function () {
  this.name = new ReactiveVar();
  Meteor.call("getNames", function(error, result) {
    if(error){
      alert("Oops!!! Something went wrong!");
      return;
    }
    this.name.set(result);
  // bind the template instance to the callback `this` context
  }.bind(this));
});

You could also use a local variable captured by a closure (you'll often see this style in JS projects) :

Template.Home.onCreated(function () {
  // use an alias to `this` to avoid scope modification shadowing
  var template = this;
  template.name = new ReactiveVar();
  // the callback is going to capture the parent local context
  // it will include our `template` var
  Meteor.call("getNames", function(error, result) {
    if(error){
      alert("Oops!!! Something went wrong!");
      return;
    }
    template.name.set(result);
  });
});
like image 200
saimeunt Avatar answered Feb 12 '23 19:02

saimeunt