chackerian
chackerian

Reputation: 1401

HTTP.get not providing data in time

I'm trying to display the users location with the help of ipinfo.io. I created a meteor server method:

 ipLocate: function() {
      HTTP.get("http://ipinfo.io", function(error, result) {
        var place = JSON.parse(result.content);
        city = place.city;
        state = place.region;
      });
        return [city,state];
    }

Which returns the city and state of the user (but only on the second time it's executed).

I made a global helper

Template.registerHelper('locationFull', function() {

      // if (!Meteor.userId()) {

      Meteor.call('ipLocate', function(error, result) {
        response = result
        Session.set('location', response);
      })
      return Session.get('location');
}

Which currently displays nothing.

If I manually run the HTTP.get request (from my ipLocate method) in the client, it returns the city and state but only after I run it twice.

How can I get the city and state to be returned in my global helper on page load.

Upvotes: 0

Views: 35

Answers (2)

chackerian
chackerian

Reputation: 1401

I ended up putting my HTTP call in a Template.onCreated() and returned the variable set with a Session var within the global helper.

Like:

 Template.registerHelper('locationFull', function() {
    return Session.get('locate');
  });

This worked.

Upvotes: 0

Stephen Woods
Stephen Woods

Reputation: 4049

This is because you're running the request asynchronously. Since your return code is outside of your HTTP.get callback (and it needs to be, it would throw an error otherwise), there is no value. The reason it returns a value on the second time is because you declared city and state as global variables (no var qualifier in front of them). The proper way to do this is to store the data you get back in a Mongo collection that is published to the client template. Checkout the Meteor Guide if you don't know how to store and publish data.

Upvotes: 1

Related Questions