Data not being loaded when I hit refresh

I have a code something like this below. I am able to print value of x when I load the template for the first time, However, when I hit refresh, the output is shown as undefined. In order for me to see x again I have to load another template and reload this template. Can anyone tell me why this is the case?

`Template.sometemplate.onCreated(function () {
    Meteor.subscribe("collection");

})

Template.sometemplate.onRendered(function () {
    var x= Collection.findOne({_id:"Something"})

    Console.log(x)

})`

The subscription is likely not ready.

Basically, you need to ensure the subscription is ready before performing your findOne. A common pattern is to set up an autorun to track the ready() method on the subscription handle. Alternatively, if you use a template helper to do the findOne, then your Blaze template will render the result when the data is available.

Check also the Template.instance documentation for some other examples using subscriptionsReady.

Thank you.

I ended up using

this.autorun(function() {

in Template onRendered

1 Like