get Meteor.subscribe in callback

74 views Asked by At

I have this code,

Meteor.subscribe('getOrgDetail', {status:'active'},function(){
        var sub = this;
        self.setState({'subscriptions.orgs':sub{id:Organizations.find().fetch()});
    });

I am using this, to get the Meteor.subscribe in callback. But it is not working. Is there any other way to setState the subscription?

1

There are 1 answers

2
Jesper We On BEST ANSWER

It looks like you are confusing things. You basically only need the subscription object if you want to .stop() the subscription.

When the last argument to .subscribe() is a function, it is interpreted as the onReady() callback.

The this context of the callback will not be the subscription object. It will be whatever is the owning context where the function is called, as usual in Javascript. And in the case of a Meteor subscription onReady callback this is not defined.

So in the callback you cannot rely on this, only on variables you have in your scope or closures (like your self).

If you want to do a .find() when the subscription is ready, what you should do is set a state flag signalling that it is, and then have a function that depends on the value of this state flag that does the .find() on the collection object, not the subscription object.

self.setState( { getOrgDetailReady: true } );

then in one of the lifecycle methods that run when state changes (which one depends on your code...) you do:

if( this.state.getOrgDetailReady ) {
    let orgDetails = orgDetailCollection.find().fetch();
    ...
}