[Solved] HTTP callback can't view data

Dear All, I’m new in meteor and I had an issue with callback json but can not loop in view.
// On Create

Template.hello.onCreated(function helloOnCreated() {

  // counter starts at 0

  var targetUrl = 'http://localhost:8000/unit.json.do';
  var rs = [];
  HTTP.get(targetUrl, function (err, result, next) { 
    console.log(result);
    rs = result;
  });

  this.counter = new ReactiveVar(0);
  console.log(rs); 
  this.itemlist = rs;
  
});

// Helper

Template.hello.helpers({
  counter() {
    return Template.instance().counter.get();
  },
  itemlist() {
    return Template.instance().itemlist.get();
  },
});

// View

    {{#each itemlist}}
      <h2>{{> codes_id}}</h2>
    {{/each}}

Any help please support me.

You don’t appear to need counter - that’s just a hang-over from the default app.

itemList becomes your reactive variable in this example, and you set it inside the callback (btw, there’s no next). Note I used “fat arrow” syntax to preserve this inside the callback.

Template.hello.onCreated(function helloOnCreated() {

  this.itemlist = new ReactiveVar();

  var targetUrl = 'http://localhost:8000/unit.json.do';
  HTTP.get(targetUrl, (err, result) => { 
    console.log(result);
    this.itemlist.set(result);
  });
});

// Helper

Template.hello.helpers({
  itemlist() {
    return Template.instance().itemlist.get();
  },
});

Your Blaze template also doesn’t look quite right to me - I suspect codes_id isn’t a new template, but is a field from the itemList. Note that it’s preferable to use the form of #each as below:

    {{#each itemlist as item}}
      <h2>{{item.codes_id}}</h2>
    {{/each}}

Note also that by using #each, the helper should return either an array of objects, or a cursor. If your url isn’t returning an array, this will not work.

After I follow above, I still met an error from console as below.

You need the decoded content, which is available in data:

this.itemlist.set(result.data);

Thanks @robfallows for your helpfull, now it is working follow your support and hear is the result.

// onCreate

Template.hello.onCreated(function helloOnCreated() {
    this.itemlist = new ReactiveVar();

    var targetUrl = 'http://localhost:8000/unit.json.do';

    HTTP.get(targetUrl, (err, result) => {
      console.log(result);
      this.itemlist.set(result.data);
    });
  
});

// Helper

Template.hello.helpers({
  itemlist() {
    return Template.instance().itemlist.get();
  },
});

// View

    {{#each itemlist}}
        <p>{{codes_id}}</p>
    {{/each}}

image

1 Like