Search code examples
javascriptd3.jsmeteoriron-router

MeteorJS : Template rendered & Meteor method call


This question follows my previous one : Meteor: How to publish custom JSON data

I created a Meteor method building a complex JSON (built with different collections etc.). With those datas I need to build a chart using D3.js.

I used to set the data in the Session but as I realized they need to be refreshed each time I am reaching the page, it does not work properly.

Obviously there is something I did not understand in the mechanics, but here is my code :

Template.myPage.rendered = function(){

    var data = Meteor.call('myData');

    var svgContainer = d3.select("#svg");

    var margin = 40;
    var width = parseInt(d3.select("#svg").style('width'),10);
    var height = parseInt(d3.select("#svg").style('height'),10);
    // ... some more D3 code where I need the data

The error I'm getting is :

"Exception from Tracker afterFlush function: data is undefined

I have already tried to call the Meteor Method outside the Template and put the result in the Session (in the callback function), but it did not work. I've also tried to use reactive var, but I couldn't make it.

Thanks a lot.


Solution

  • Thanks to twitter and @callmephilip I found the answer (and I am ashamed I couldn't find it myself ! :D)

    The only thing to do is to put all the d3 code inside the method callback :

    Template.myPage.rendered = function(){
        Meteor.call('myData', function(err, result){
            if(err){
               console.log(err);
            }else{
                 // all the D3.js code 
            }
        });
    };
    

    Have a good day ;)