Send data to template based on ReactiveVar (or session variable)


#1

I have a collection of questions and want to iterate through them based on a next button. I can update a ReactiveVar or session variable named ‘counter’ but when I pass the variable to the Template helper, I get an error that the variable is undefined.

Thanks or your interest!

JS Code:

Session.setDefault(‘counter’, 0);

Template.contestQuestion.helpers({
counter: function () {
return Session.get(‘counter’);
},

question: function () {
return Questions.find({order: counter});
}

});

Template.contestQuestion.events({
‘click .next’: function () {
// increment the counter when button is clicked
Session.set(‘counter’, Session.get(‘counter’) + 1);

}
});


#2

You could put in a guard.

Template.contestQuestion.helpers({
    counter: function () {
        var counter= Session.get('counter');
        return (typeof counter === 'number' ? counter : 0);
},

#3

in the “question” helper you would need to call it as Session.get(‘counter’)

or if it is template scoped ReactiveVar than Template.instance().counter.get()


#4

Thanks for the prompt response but I am still getting counter undefined error.


#5

I tried your suggestion in this way:
Template.contestQuestion.helpers({

question: function(){
return Questions.find({order: Session.get(‘counter’)});
}
});

I am getting neither error or response.


#6

you can try what it is returning in browser console, but add .fetch() at the end, cause it is cursor without it.

So you are getting these data from helper:

Questions.find({order: Session.get('counter')}).fetch();

I believe there should be some results, maybe you are just using them wrong way, but template iteself was not part of yout report so far…


#7

OK. it is working now. I had initialized variable with session.setdefault so it wasn’t updating. Switched to session.set.
I’m going to try to refactor with template scope.

Thanks!