Fred J.
Fred J.

Reputation: 6029

How to reactively call a Meteor method referenced by a reactive variable?

I am trying to invoke a Meteor method not with a hard-coded string but with a Session variable which contains its name. It works once but does not re-run the method when the Session value is changed via Session.set.

Server code:

Meteor.methods({
  hello: function () {
    console.log("hello");
  },
  hi: function () {
    console.log("hi");
  }
});

Client code:

Session.set('say', 'hi');
Meteor.call(Session.get('say'));  // console prints hi
Session.set('say', 'hello');      // console is not printing, expected hello

How can I get the "new" method to be called after the Session value is changed, reactively?

Upvotes: 1

Views: 771

Answers (1)

Kyll
Kyll

Reputation: 7139

You need a reactive context to achieve this kind of home-made reactivity.
You can achieve this simply with Tracker.autorun:

Session.set('say', 'hi');

Tracker.autorun(function callSayMethod() {
  Meteor.call(
    Session.get('say')
  );
});

Meteor.setTimeout(
  () => Session.set('say', 'hello'),
  2000
);

Spacebars template helpers use that kind of context to achieve reactivity in templates.

Note that you don't need Session here. A simple ReactiveVar would be enough:

const say = new ReactiveVar('hi');

Tracker.autorun(function callSayMethod() {
  Meteor.call(
    say.get()
  );
});

Meteor.setTimeout(
  () => say.set('hello'),
  2000
);

Upvotes: 3

Related Questions