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.