Ramin Melikov
Ramin Melikov

Reputation: 1005

Why is my D3.csv() method is getting back "undefined"

I just have a csv file and I'm trying to get the data with an async function but I'm getting undefined.

<script>
    async function data(pathToCsv) {
        return await d3.csv(pathToCsv, function (data) {
            data.year = +data.year
            data.running_total = +data.running_total
            data.date = new Date(data.year, 0)
            return data
        })
    };
    let dataset = data('q3.csv');
    console.log(dataset.year);
</script>

Upvotes: 1

Views: 1357

Answers (2)

Ramin Melikov
Ramin Melikov

Reputation: 1005

I solved it.

<script>

    async function data(pathToCsv) {
        let dataset = await d3.csv(pathToCsv, function (d) {
            d.year = +d.year
            d.running_total = +d.running_total
            d.date = new Date(d.year, 0)
            return d
        })
        return dataset
    };

    data('q3.csv').then(function(d) {
        d.forEach(function(p){
            console.log(p.date.getFullYear());
        })
    });

</script>

Upvotes: 0

ehab
ehab

Reputation: 8064

The issue here is that your data function is returning a promise, and so accessing year from a promise object will return undefined, you need to add await when calling your data function

 async function data(pathToCsv) {
        return await d3.csv(pathToCsv, function (data) {
            data.year = +data.year
            data.running_total = +data.running_total
            data.date = new Date(data.year, 0)
            return data
        })
   };

  async function init() {
     let dataset = await data('q3.csv');
     // this should work now assuming you are using d3 function correctly as i'm not aware of d3 functions myself
     console.log(dataset.year); 
  }

  init()

Upvotes: 2

Related Questions