Pubudu Jayawardana
Pubudu Jayawardana

Reputation: 1

Meteor method on page load

I need to load some list of data from db on page load. I have used Template.layout.helpers and call a method from server. However the data not rendered on template but in helper function retrieved data can be seen in console. What am I missing here?

server

Posts = new Mongo.Collection("posts");
Meteor.methods({
    'getposts':function(){
        Future = Npm.require('fibers/future');
        var future = new Future();
        console.log('getposts called');
        var posts = Posts.find({_id:"ThnBjGkFEQJ3CZ47d"}).fetch();
        future.return(posts);
        return future.wait();
    }
});

client

Posts = new Mongo.Collection("posts");
Template.layout.helpers({
    'posts': function () {
        Meteor.call('getposts', function (error, response) {
            console.log(response[0]);
            console.log('xxxx');
            return response[0];
        });
    },
    'tests': function () {
        var x = { title:"ioioioioio", description:"ioioioioio", _id:"ThnBjGkFEQJ3CZ47d"};
        console.log(x);
        console.log('yyyy');
        return x;
    }
})

template

<template name="layout">
    <div class="post">
        xxxx
        {{posts.title}}
        ----
        {{tests.title}}
        yyyy
    </div>
</template>

Upvotes: 0

Views: 319

Answers (1)

ajduke
ajduke

Reputation: 5057

Try use the Meteor publish-subscribe, in this case

On client side,

Meteor.startup(function(){

   Meteor.subscribe('posts')
})

and server side use

Meteor.publish('posts', function(){
  // this according to your code 
  return Posts.find({_id:"ThnBjGkFEQJ3CZ47d"});

})

and on helpers, just call this

Template.layout.helper({
  posts: function(){
    return Posts.find()
  }

})

This above code will work reactively

Upvotes: 1

Related Questions