Pradeep Saini
Pradeep Saini

Reputation: 740

how to return meteor call value in helper in meteor

I have pass id to helper from html and my helper is getusername

getusername(id) {
    var username = "";
    Meteor.call("getUserName", id, function(error, result) {
        if (error) {
            console.log("error", error);
        }
        if (result) {
            console.log(result);
            username = result;
        }
    });
    return username;
}

while i log the result its log what i need but in UI no username visible. and when i use this with Reactive var its become infinity ... because when reactive variable value change its execute again...

Upvotes: 2

Views: 663

Answers (2)

Waiski
Waiski

Reputation: 9680

You cannot asynchronously fetch data and return it from the same helper, because the helper returns before the call is complete and there is no reactive variable to indicate that the data has changed once the call is complete. You are right about using ReactiveVar, but to avoid infinite loop you must run Meteor.call outside the template helper. I'd recommend doing it in the template's onCreated hook:

Template.x.onCreated(function() {
  var self = this;
  Meteor.call("getUserName", this.data.id, function(error, result) {
    if (result) {
        self.username = new ReactiveVar(result);
    }
  });
});

Template.x.helpers({
  getUserName(id) {
    return Template.instance().username.get();
  }
});

Note, however, that in almost all cases it's better to do things like fetching an user's name directly in the front-end like return Meteor.users.findOne(id).profile.name or something, as this is reactive and easier.

Upvotes: 3

Ashish Patel
Ashish Patel

Reputation: 941

because of async behavior you wont get the return value what you can do is set the return value in session and get it from session where ever you want

getusername(id) {
    var username = "";
    Meteor.call("getUserName", id, function(error, result) {
        if (error) {
            console.log("error", error);
        }
        if (result) {
            console.log(result);
            username = result;
        }
    });
    Session.set('getUserNameResult', result);
}

Upvotes: 2

Related Questions