0

I do have a template and i'm trying to display a variable which should be modified from a method

Heres how my code looks like

The html

{{test}}

The server:

if (Meteor.isServer) {
    Meteor.methods({
        callApi: function (term) {
            this.unblock();
            try {
                const result = HTTP.call('GET', 'https://www.googleapis.com/youtube/v3/search')
                return result;
            } catch (e) {
                // Got a network error, timeout, or HTTP error in the 400 or 500 range.
                console.log(e);
                return false;
            }
        }
    });
}

The client

    Template.body.helpers({
        test: 'test'
    });
Template.body.events({
        'submit .media-Search'(event, template) {
            // Prevent default browser form submit
            event.preventDefault();

            // Get value from form element
            const target = event.target;
            const text = target.text.value;

            Meteor.call("callApi", text, function(error, results) {
                if (error)
                    console.log(error);

                template.test = results.data.items[0].snippet.channelId; //results.data should be a JSON object
            });

            // Clear form
            target.text.value = '';
        },
    });

The variable does change but the change is not shown on the html page, What am i doing wrong?

Much appreciated!

1 Answer 1

2

Your need to store your Meteor method result in a reactive variable / reactive dictionary:

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

Template.body.onCreated(function() {
    this.test = new ReactiveVar(); // create reactive var

})

Later in your submit event:

// ...
Meteor.call("callApi", text, function(error, results) {
    if (error) console.log(error);

    // set value for reactive variable
    template.test.set(results.data.items[0].snippet.channelId);
});

Your template helper is currently a string (I wonder that the build system does not throw an Error on this) but should be a method that returns your updated reactive variable:

Template.body.helpers({
    test() {
        return Template.instance().test.get();
    }
});

You should read some more on Blaze and ReactiveVar documentation:

http://blazejs.org/

https://docs.meteor.com/api/reactive-var.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.