When running onCreated, declare ReactiveVar instance variable and invoke server side method by Meteor.call, and set data to ReactiveVar instance variable in Metelr.call’s callback.
Then, get ReactiveVar instance variable and reflect view in helper method.
In the following cases,
onCreated -> autorun -> Meteor.call -> show -> callback -> show
I would like to operate in the order, but the last show method doesn’t work despite setting defferent value in callback.
please give me some advice…
# page.js
Template.page.helpers({
getData(){
return Template.instance().count.get();
}
});
Template.page.onCreated(function() {
this.count = new ReactiveVar(0);
Tracker.autorun(() => {
Meteor.call('serverMethod', (error, users) =>{
let count = this.count.get();
for( user of users){
count++;
}
this.count.set(count) //set number other than 0.
});
});
});
# page.html
<span class="data">Data: {{getData}}</span>
Also, I see you’ve corrected your code and added more in the autorun, which now looks somewhat dangerous to me: geting and setting the same reactive variable in an autorun can result in an infinite loop:
An autorun will always run the “enclosed” code once, and will re-run it if a dependent, reactive variable changes.
In your case, the dependent, reactive variable is count: you will re-run the autorun every time you do this.count.set(count) with a different value of count.
As a first step, try removing the autorun - it’s not needed here anyway:
Template.page.onCreated(function() {
this.count = new ReactiveVar(0);
Meteor.call('serverMethod', (error, users) =>{
let count = this.count.get();
for( user of users){
count++;
} // if users is an array you could do count += users.length in place of this loop
this.count.set(count) //set number other than 0.
});
});
Oh - you did do meteor add reactive-var to your project?