notthehoff
notthehoff

Reputation: 1242

How to ensure template helper has data?

I have a select box that runs a small method on each option to determine what 'selected' is:

      <label for="soft-due-date-controller">Soft Due Days:</label>
      <select class="form-control" id="soft-due-date-controller">
        <option value="0" {{determineDefaultSelect '0'}}>0</option>
        <option value="1" {{determineDefaultSelect '1'}}>1</option>
        <option value="2" {{determineDefaultSelect '2'}}>2</option>
        <option value="3" {{determineDefaultSelect '3'}}>3</option>
        <option value="4" {{determineDefaultSelect '4'}}>4</option>
        <option value="5" {{determineDefaultSelect '5'}}>5</option>
        <option value="6" {{determineDefaultSelect '6'}}>6</option>
        <option value="7" {{determineDefaultSelect '7'}}>7</option>
        <option value="8" {{determineDefaultSelect '8'}}>8</option>
        <option value="9" {{determineDefaultSelect '9'}}>9</option>
        <option value="10" {{determineDefaultSelect '10'}}>10</option>
      </select>

Here is the method:

determineDefaultSelect: function(optionText){
    let savedSoftSchedueDays = SoftDueDates.find().fetch()[0].currentSoftMargin;
    if(optionText == savedSoftSchedueDays){
        return "selected";
    }
},

On the client side... it ends up loading appropriately and responsively updates in the dropdown when I update the db directly. My problem is that I am getting the following error on load multiple times on load:

Exception in template helper: TypeError: Cannot read property 'currentSoftMargin' of undefined

While it works, this error does not seem right and this is the only place in the code where currentSoftMargin is used. Almost like the template helper determineDefaultSelect is running faster than the db call can happen and a product async calls... maybe? Can I prevent this?

Upvotes: 0

Views: 36

Answers (2)

fnkrm
fnkrm

Reputation: 498

Use {{#if Template.subscriptionsReady}}{{/if}} in your template to ensure all the data needed are ready.

Upvotes: 1

Michel Floyd
Michel Floyd

Reputation: 20236

You're getting this error when the helper runs before the subscription to your data is ready(). You can either wait for the subscription is ready to render the template (rendering a spinner in the meantime instead) or defend against the runtime error:

determineDefaultSelect: function(optionText){
  const doc = SoftDueDates.findOne(); // equivalent to .find().fetch()[0];
  const savedSoftScheduleDays = doc && doc.currentSoftMargin; // will not error
  return (optionText == savedSoftScheduleDays) ? "selected" : ""; // shorthand
},

Upvotes: 1

Related Questions