Meteor method not returning html to template


#1

I’m trying to show a alert warning for when a user first logs in, after their first login then I don’t want this message shown. So I’ve created this method:

Meteor.methods({
'firstLogin': function() {
    if (Meteor.user().loggedInTimes === 0) {
        return '<div class="alert alert-info alert-dismissible alertBar" role="alert"><br><button type="button" class="alertButton" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><b>Please take a few minutes to personalise your experience at SSAW by updating your <a href="/profile" class="alert-link hoverAlert">profile</a></b>. </div>';
        }
    }
});

I call it in Meteor.isClient as:

if (Meteor.isClient) {
    Template.myHome.helpers({
        count: function(){
        var user = Meteor.user();
        //console.log(user);
        if (user) {
            Meteor.call('firstLogin');
            }
        }
    });
}

This is the template:

<template name="myHome">
    <div class="container">
        {{{ count }}}
        <div class="text-center">
            {{#if currentUser }}
                <h1 class="roboto">Hi{{ username }}</h1>
           {{/if}}
        </div>
    </div>
</template>

However this does not render any of the html from the method. How can I get the html alert message to appear?


#2

Meteor.call on the client is asynchronous. Read docs.meteor.com it gives examples


#3

As @jamgold said, Meteor.call on the client is asynchronous.
You create a reactive variable in the template’s onCreated callback.
After that you call Meteor method.
When the method finishes its execution, you update reactive variable with the value returned from the server.
I think it helps you.
If you want to investigate further, you can look at this stack overflow discussion.

if (Meteor.isClient) {

 Template.hello.onCreated(function() {

    this.loggedInTimes = new ReactiveVar("loading logged in times...");
    
    Meteor.call("loggedInTimes", (error, result) => {
      this.loggedInTimes.set(result);
    });
  });

//You return simply your reactive variable from the template helper.
Template.hello.helpers({
    count: function () {
      return Template.instance().loggedInTimes.get();
    }
  });

}

if (Meteor.isServer) {
  Meteor.methods({
    loggedInTimes: function() {
      return 999;
    }
  })
}

Template:

<head>
  <title>test</title>
</head>

<body>
  {{> hello}}
</body>

<template name="hello">
  {{count}}
</template>

#4

Thanks…using the reactiveVar was what I needed.