Search code examples
meteorscopetrackerddp

MeteorJS Tracker: How to return a value after subscription?


Got this problem with the Tracker.autorun() method:

Template.registerHelper('getUserName', (userId) => {

    let userName = '';
    Tracker.autorun((tracker) => {
        if (userId) {
            let subscription = Meteor.subscribe('userName', userId);
            if (subscription.ready()) {
                tracker.stop();
                let user = Meteor.users.findOne({_id: userId}, {fields: {emails: 0}});
                userName = user.services.facebook.name;
            }
        }
    });
    return userName;

});

I want to return the username from the publication, however, the scope is tricky because the helper returns an empty string while the Tracker is still subscribing to the data.

I've tried this:

Template.registerHelper('getUserName', (userId) => {

    let subscription;
    Tracker.autorun((tracker) => {
        if (userId) {
            subscription = Meteor.subscribe('userName', userId);
        }
    });
    if (subscription.ready()) {
        let user = Meteor.users.findOne({_id: userId}, {fields: {emails: 0}});
        return user.services.facebook.name;
    }

}); 

But the subscription has no method .ready() yet.

Any ideas on how to work with scopes here? I remember closures can be useful.


Solution

  • I think you want to move your subscription out of your helper. This is better left to templates invoking the helper in the onCreated() function. Check out this link for help: http://guide.meteor.com/data-loading.html

    So you helper would look like:

    Template.registerHelper('getUserName', (userId) => {
        let user = Meteor.users.findOne({_id: userId}, {fields: {emails: 0}});
        if( user && user.services && user.services.facebook) {
            return user.services.facebook.name;
        }
    });
    

    And then in your template you'd do:

    {{#if getUserName currentUser}}
        <!-- Your code here. -->
    {{else}}
        <!-- What to do if you don't have a user defined yet. -->
    {{/if}}