user1377371
user1377371

Reputation:

Update meteor template if data changed

I have blaze template for city popular places names listing:

<template name="city">
  {{#each places}}
    {{this}}
  {{/each}}
</template>

and helper from where i trying to get places data from GoogleMaps for template:

Template.city.helpers({
    places: function() {
        if (GoogleMaps.loaded()) {
            var places = [];
            ...

            service.radarSearch(request, function(points) {
                points.slice(0, 8).forEach(function(point) {
                    service.getDetails({
                        placeId : point.place_id
                    }, function(details) {
                        places.push({
                            name: details.name
                        });
                    });
                });
                return places; 
            });
        }
    }
})

But it doesn't work because template rendered before helper array with data is ready. What i should be done to make helper returned data reactive and display this data in template?

Upvotes: 1

Views: 638

Answers (1)

user105375
user105375

Reputation:

Use the onRendered hook to assign results to a reactive variable on the template instance:

import { ReactiveVar } from 'meteor/reactive-var';
Template.city.onRendered(function() {
  const self = this;
  self.places = new ReactiveVar();
  service.radarSearch(request, function(points) {
    self.places.set(places);
  }
});

From there, it's just a matter of returning that reactive variable from the helper:

Template.city.helpers({
  places: function() {
    const tpl = Template.instance();
    const places = tpl && tpl.places.get();
    return places || [];
  }
});

Upvotes: 3

Related Questions