Search code examples
javascriptd3.jses6-promise

Getting 'TypeError: Cannot read property 'then' of undefined' when loading data using d3


I have two classes in my code, both of which use d3. There is my main class, Main.js, and it instantiates an instance of another class, Data.js, which loads data from a csv and then applies d3.nest to it. I am getting an "Uncaught TypeError: Cannot read property 'then' of undefined." from the promise in the main class.

Here is the relevant code in the main class:

this.data = new Data();

this.mainChartData = this.data.loadNestedData().then(nestedData => {  // error
  console.log(nestedData);
});

Here is the Data class:

class Data {
  constructor() {}

  loadNestedData() { d3.csv("data.csv").then((loadedData) => {
      console.log(loadedData);  // this logs correctly
      this.nestedData = d3.nest()
         .key(function(d) { return d.gameID; })
         .entries(loadedData);
      console.log(this.nestedData); // this logs correctly
      return this.nestedData;
  });
}

Solution

  • You are missing a return here:

    loadNestedData() { d3.csv
    

    Should be

    loadNestedData() { return d3.csv