JSReport - chart not rendering with dynamic values

1k Views Asked by At

I am able to fetch data through REST API using JSReport Script. I am able to display pie chart using template engine(recipe: html, engine: handlebars) with hardcoded values. Now i have to pass dynamic data from JSreport Script to Template engine. I am not sure how to do it.

Script

async function prepareDataSource() {
    const extracts = await fetchStats() . // REST API Call
   // console.log(extracts.data);
    let arr = extracts.data
     let statsbySale = d3.nest()
                .rollup(function(d) {
                    return {
                    A : d3.sum(d, function (g) { return g.a; }),
                    B : d3.sum(d, function (g) { return g.b; }),
                    C : d3.sum(d, function (g) { return g.c; }),
                    D : d3.sum(d, function (g) { return g.d; })
                };
                }).object(arr);
                console.log(JSON.stringify(statsbySale)); ==> returns ["A" : 10, "B" : 20, "C" : 30, "D" : 40]
                return (JSON.stringify(statsbySale))
}


async function beforeRender(req, res, done) {
     req.data.sales = await prepareDataSource()
     console.log(req.data.sales======>Printed the same JSON object as above
     done();
}

==================================

Template engine

<script>
    Chart.defaults.global.legend.display = false;
    new Chart(document.getElementById('myChart').getContext("2d"),            
        type: 'pie',
        data: {
             labels: ['A', 'B', 'C', 'D'],
             datasets: [{
                  backgroundColor: [
                      'green',
                      'orange',
                      'yellow',
                      'purple'
                  ]                
                  borderColor: "rgba(27,161,226,1)",
                  borderWidth: 1,
                  hoverBackgroundColor: "rgba(27,161,226,0.4)",
                  hoverBorderColor: "rgba(27,161,226,1)",
                  data: [10,20,30,40] ===>Hardcoded value
                }]
        },
        options: {
             animation: {
                 duration:            
             }
        }
});
</script>

How to pass the dynamic value from Script file to template engine to render the chart properly.

1

There are 1 best solutions below

0
Jan Blaha On

The solution can be found here.

You need to serialize json data using custom templating engine helper and write them to the inline script.

Define custom helper

function toJSON(data) {
  return JSON.stringify(data);
}

Write data to the inline script

<script>
  var data = {{{toJSON sales}}}
  ... your chart using data
</script>