SteveSong
SteveSong

Reputation: 311

Import CSV files in Nuxt.js framework for processing by D3

I am trying to integrate a D3 chart into the Nuxt framework (am very new to Nuxt) and a problem I have run into is how to make a number of CSV files available to the DOM to be graphed by D3. IN D3 this is a simple call to the CSV function:

 d3.csv('myData.csv, function (error, myData) {
    if (error) throw error }

Performing this simple function in the Nuxt.js framework is proving to be hard work (for me). First I tried to load them using the d3.csv function in the mounted: section of the script:

<script>
  import * as d3 from 'd3'
  export default {
    mounted () { 
      d3.csv('myData.csv, function (error, myData) {
         if (error) throw error }
      }
    }
</script>

but neither the variable myData or this.myData is available to the DOM when loaded this way. I guess because that loads afterwards?

It seems like the Vuex store might do the job but for the life of me I cannot find the right syntax for loading the CSV and ensuring that the program waits for the CSV file to be loaded.

Is there a canonical way to load data files like this in Nuxt? Even better if someone could point to an example of something similar that I might learn from?

Upvotes: 1

Views: 1745

Answers (1)

SteveSong
SteveSong

Reputation: 311

Grateful to Sebastian Kolinks for providing the answer. The problem was that the d3.csv function was stealing the context from Vue.js, overwriting this with its own version.

d3.csv('myData.csv', function (myData) {
  this.myArray = freqData  // throws "this" is undefined error
})

By using an arrow function which doesn't have its own this, the problem was solved.

d3.csv('myData.csv', (myData) => {
    this.myArray = freqData   
  })

Sebastian's example code is at https://jsfiddle.net/L6osr9ve/

Upvotes: 1

Related Questions