Can we set Reactive Vars in helpers?

If can please explain.

Yes, you can, but you need to be careful. Helpers are reactive, which means they will re-run if any of the reactive data they use changes. So, if you mutate a ReactiveVar which you are using to return data from, then you risk an infinite loop. For example, this is unsafe:

Template.hello.onCreated(function helloOnCreated() {
  this.counter = new ReactiveVar(0);
});

Template.hello.helpers({
  result() {
    const t = Template.instance();
    const newValue = t.counter.get() + 1;
    t.counter.set(newValue);
    return newValue;
  },
});
5 Likes

Thank you for the answer. I solved my problem with sessions and meteor timer for now.

Okay, but Session variables are no different in that regard than Reactive Vars. You still need to ensure you don’t read and mutate in the same helper.

3 Likes

My general pattern (widely used afaik) is to ensure you are mostly consuming reactive data sources in template methods (bound in onCreated), and managing the source flow of all reactive data to ensure no “crossover” as mentioned above. This makes helpers begin to be very simple, since as also mentioned any and all reactive data sources will trigger the tracker for the helper, and can easily become overly recursive, or event infinite.