Loading the content of JSON in template

Hello,

I have JSON response from external php file. I have helper function which calls the remote method to get the JSON data.

Template.products.helpers({

    'showproducts' ()
    {
           // Remote method has HTTP function which fetches the JSON response.
            Meteor.call("getproducts",function(error, result)
            {
                  // This works perfectly. Shows in console
                   show = result.data.products[0];
                   console.log(show);
            });
    },
    
});

Added {{showproducts}} in template but not working.

This doesn’t work.

 Template.products.helpers({

        'showproducts' ()
        {
               var show;
               // Remote method has HTTP function which fetches the JSON response.
                Meteor.call("getproducts",function(error, result)
                {
                      
                       show = result.data.products[0];
                       
                });
                return show;
        },
        
    });

This doesn’t the value. I guess the problem is that it takes few seconds to load JSON data.
How can I do this ? Please help.

Thank You!

You need to use a reactive variable to allow the helper to rerun when the call completes:

Template.products.onCreated(function() {
  this.response = new ReactiveVar();
  Meteor.call('getproducts', (error, result) => {
    // Remote method has HTTP function which fetches the JSON response.
    // This works perfectly. Shows in console
    const show = result.data.products[0];
    this.response.set(show);
    console.log(show);
  });
});

Template.products.helpers({

  'showproducts'() {
    const instance = Template.instance();
    return instance.response.get();
  },

});

Note that the call is made in the onCreated and the helper just gets the (latest) value from the ReactiveVar.

You will need to meteor add reactive-var to your project, if you haven’t already.

1 Like

Thank you so much sir. Now I understood clearly why reactive-var is used. Thanks again. :slight_smile:

1 Like

You said you get the data from Remote method has HTTP function fetches the JSON response.
Can you tell me, remote means Rest server?
If you used it can you tell me how to get the response from Remote server’s.

I made a method on server called getproducts which uses the HTTP.call function to get the response from the remote server. And then I called remote Meteor.call(“getproducts”) from client side to get the response. You can’t directly use HTTP.call on client side because chrom browser won’t allow you.

Thank you, i will look in to it.