Daltron
Daltron

Reputation: 1856

Return an array from a collection, create variables from strings, and pass that array to a dynamic template helper?

I'm writing in MeteorJS.

Okay, so I first make a call to the server and get back an array of values from a collection.

var result = ["First", "Second"];

I then need to turn these values into variable names to pass to a template using spacebars. I used a for loop for this:

newArray.push(window[result[i]]);

This gives me back an array of indexes. Now, the problem is, I need to then pass this array of indexes to my dynamic template through spacebars. The problem is, I need my template helper to wait for the values, and then the conversion, and then return the array of indexes. Here is my code using the deanius:promise package for callPromise:

Template.auto.helpers({

returnIndexNames: () => {

var newArray = [];

Meteor.callPromise("getIndexNames", function(error, result){
if (result) { return result; }}).then((result) => {
  for (let i=0; i<result.length; i++) {
    newArray.push(window[result[i]]);
  }
});

var checkArray = setInterval(function() {
  if (newArray.length > 0) {
    clearInterval(checkArray);
    return newArray;
  }
}, 200);

How can I pass this array back through the helper to:

{{#each returnIndexNames}}

{{/each}}

Any help is appreciated! (I'm sure it's something easy and I'm dumb).

Upvotes: 2

Views: 49

Answers (1)

Albert James Teddy
Albert James Teddy

Reputation: 1375

You should not use any kind of interval for handling promises, it is not necessary.

Once your promise resolves, the then() function is called. Here you should set the value of a ReactiveVar with the results of your promise. Moreover, your promise call shouldn't be made in the helper directly.

Keeping your variable names, you could use:

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

import './main.html';

Template.auto.onCreated(function autoOnCreated() {
  this.indexNames = new ReactiveVar([]);
  Meteor.call('getIndexNames', (error, result) => {
    this.indexNames.set(result);
  });
});

Template.auto.helpers({
  returnIndexNames() {
    return Template.instance().indexNames.get();
  },
});

The code is adapted from those references:

Upvotes: 1

Related Questions