简体   繁体   中英

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...

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM