Search code examples
javascriptmeteorspacebars

Calling helpers before template rendered


I am building a meteor project where I need to keep all my collections non reactive. So I have removed both subscribe and publish. To show any information from DB, my helpers are calling a method in meteor.call. But in my case, the template is not being able to show the info from DB, because the template is being rendered before a anything is returned from DB. Can anyone suggest a good way to display information from Meteor.call methods in templates WITHOUT USING SESSION.

Here is my code. My Template code

    <template name = "showEmployeeFromRouter">
    {{#each allEmployee}}
        <div>
            Name: {{name}}
            <br>
            Org: {{org}}
        </div>
        <br><br>
    {{/each}}
  </template>

Helper code

    Template.showEmployeeFromRouter.helpers({
    allEmployee:function(){
        //return [{name:"AX",org:"XS"},{name:"XS",org:"SE"}];
       Meteor.call('showAllEmployees',function(err,res){
           if(res){
               console.log(res);
               return res;
           }
       });
    }
})

Code in the server

Meteor.method({
        showAllEmployees:function(){
        var obj = Employees.find().fetch();
        return obj;
       }
    });

Does any one have a proper way to for this problem.


Solution

  • Finally did it. By using reactive var or reactive Dict. My Template.

        <template name = "`showEmployeeFromRouter`">
        {{#each allEmployee}}
        <div>
            Name: {{name}}
            <br>
            Org: {{org}}
        </div>
        <br><br>
    {{/each}}
    

    My server call.

    Meteor.method({
        showAllEmployees:function(){
        var obj = Employees.find().fetch();
        return obj;
       }
    });
    

    And finally My helper.

    Template.showEmployeeFromRouter.created = function(){
    this.state = new ReactiveDict();
    var parentInstance = Template.instance();
    Meteor.call('showAllEmployees',function(err,res){
           if(res)
        parentInstance.state.set('allEmp',res);
    })}
    
    Template.showEmployeeFromRouter.helpers({
    allEmployee:function(){
        return Template.instance().state.get('allEmp');
    }});
    

    dont forget to add reactive dictionary package. meteor add reactive-dict