TheBlake
TheBlake

Reputation: 267

Trying to load simple CSV file into D3 with queue.js

I'm a newbie to web dev, and am trying to figure out how to load CSV data into D3.js, using queue.js to ensure that data is fully loaded before I execute the next step of the code (which will be drawing a chart with the data).

I have googled this endlessly, but can't seem to wrap my head around how queue.js works.

I have the following code, and can't understand why it isn't working.

//Create a queue. First load CSV data, then run a function on the data once fully loaded.
queue()
.defer(d3.csv, "Workbook1.csv")
.await(makeChart(mydata));


//create global variable 'mydata' to store CSV data;

var mydata = [];

//d3 CSV loading function - load data into global variable 'mydata' and convert test scores to numeric format.

d3.csv('Workbook1.csv', function(data) {

    mydata = data;
    mydata.forEach(function(d){ d['Test_Score'] = +d['Test_Score']; });
    console.log(mydata); 

});

//create function that will print my data to the console. Once I figure this out, I'll put in some d3 code to actually make the chart.

function makeChart(data) {
  console.log(data);
  console.log("everything ran");
 };

I get the following error in the console: "Uncaught TypeError: Cannot read property 'apply' of undefined".

I know that the function 'makeChart' is running because I get 'everything ran' as an output. But for some reason, it doesn't pass my 'mydata' variable in.

The console.log within the d3.csv function does work correctly and outputs the correct values. But console.log(data) in the makeChart function is showing up as 'undefined' in the console.

Apologies for the simplistic question, but I'm super new to this and the examples I've found from googling haven't enabled me to solve this problem.

Thanks,

J

Upvotes: 3

Views: 6037

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

You doing it like this:

queue()
.defer(d3.csv, "Workbook1.csv")
.await(makeChart(mydata));//here you are calling the function makeChart

Should have been like this:

 queue()
    .defer(d3.csv, "Workbook1.csv") 
    .await(makeChart);//only function name is needed

And Make chart function should be like this:

function makeChart(error, data) {//first param is error and not data
  console.log(data);
  console.log("everything ran");
 }; 

EDIT

If you have multiple urls it will be like this:

queue()
.defer(d3.csv, "Workbook1.csv")
.defer(d3.csv, "Workbook2.csv")
.await(makeChart);//here you are calling the function makeChart

   function makeChart(error, data1, data2) {//first param is error and not data
      console.log(data1);//workbook1
      console.log(data2);//workbook2
      console.log("everything ran");
     }; 

Hope this helps!

Upvotes: 6

Related Questions