0

I have created a DJango/ReactJS site that is attempting to display an nv.d3.js pie chart. When I add the code to display the pie chart, passing the data array directly into the code, the pie chart displays on the site correctly. However, when I use d3.json(url, callback) to retrieve JSON from the URL (served by Django views.py) and pass that as the data into the pie chart, I get an error.

The nvd3 code is:

createPieChart() {
  const node = this.node

  nv.addGraph(function() {
    var chart = nv.models.pieChart()
      .x(function(d) { return d.label })
      .y(function(d) { return d.value })
      .showLabels(true);

    d3.select(node)
      .datum(getPieData())
      .transition().duration(350)
      .call(chart);

    return chart;
  })
}

The getPieData() function is:

function getPieData() {

 // return (d3.json(url, function(error, rawData) {
 //           if (error) {
 //               console.log("error = " + error)
 //               return;
 //           }
 //           else{
 //             return rawData;
 //           }
 //         }
 //       )
 // )
   return [{"label": "R", "value": 822}, {"label": "H", "value": 1}];
 }

Notice in the above snippet, I commented out the problematic code. What I return above works. Now, if I go to the URL above that is served by Django, it returns the following data exactly like this in the browser (and in the console, I added a |safe filter after passing in the data):

[{"label": "R", "value": 822}, {"label": "H", "value": 1}]

The error I get is:

Uncaught Type Error: data.map is not a function

I would expect this to pass in the data to the addGraph function and display the chart correctly, the same way as if I pass the data directly into the graph function...

I tried returning rawData.map() in my getPieData function, but that doesn't work either. I get the same error.

altocumulus
  • 21,179
  • 13
  • 61
  • 84
Niko
  • 67
  • 1
  • 4
  • This issue has been asked many times here at S.O., but unfortunately with different flavours, which makes closing as a duplicate a delicate issue. Because of that, I just wrote a [self-answered question](https://stackoverflow.com/q/47664292/5768908), which I hope may help you. – Gerardo Furtado Dec 05 '17 at 23:22
  • By the way, you're getting this error (`data.map is not a function`) because your `data` here, as I explain in my answer, is an *object*, not an array. – Gerardo Furtado Dec 06 '17 at 00:13

0 Answers0