Setting a variable within a template event handler and reactively updating the UI

Here’s my simple template.

<template name="landingSignup">
  <form class="form-inline">
    <input type="email" name="email"/>
    <input type="password" name="password">
    <input type="submit" value="Submit">

    <p>Whoops! {{reason}}</p>
  </form>
</template>

And my handler:

Template.landingSignup.events({
  'submit form': function(event) {
    event.preventDefault();
    var email = event.target.email.value;
    var password = event.target.password.value;

    if (email !== "" && password !== "") {
      Meteor.loginWithPassword(email, password, function(error) {
        if (error && error.reason === "Incorrect password") {
          console.log("Should set the {{reason}} variable here.");
        }
      }
    }
  }
});

How can I set the {[reason}} variable in my event handler?

You can use a ReactiveVar and assign a value in the event handler and then use the ReactiveVar in your template helper.

1 Like

Try if this works

Template.landingSignup.onCreated(function(){
 this.reason = new ReactiveVar("");
});
Template.landingSignup.events({
  'submit form': function(event, template) {
    event.preventDefault();
    var email = event.target.email.value;
    var password = event.target.password.value;

    if (email !== "" && password !== "") {
      Meteor.loginWithPassword(email, password, function(error) {
        if (error && error.reason === "Incorrect password") {
          template.reason.set(error.reason);
          console.log("Should set the {{reason}} variable here.");
        }
      }
    }
  }
});
1 Like

Yeah adding a ReactiveVar fixed the issue. Thanks for the help guys.