Reputation: 513
I'm trying to load data from a CSV file in D3; I have this code:
function update (error, data) {
if (error !== null) {
alert ("Couldn't load the dataset!");
} else {
//do something
};
function changeData () {
d3.csv ("data/dataset.csv", update);
}
If I use D3 v4 it works fine, but if I switch to v5 it doesn't work anymore. Can someone explain to me how to modify the code to make it work with D3 v5?
Upvotes: 36
Views: 32116
Reputation: 2550
d3 v5 uses the fetch API and returns a promise requiring the below code.
d3.csv('yourcsv.csv')
.then(function(data) {
// data is now whole data set
// draw chart in here!
})
.catch(function(error){
// handle error
})
In case in the future people want v4. d3 v4 on the other hand uses the XMLHttpRequest method, and does not return a promise requiring this code
d3.csv('yourcsv.csv', function(data) {
//whole data set
// draw chart here
})
csv loading is async so make sure to run your chart code within the csv function.
Upvotes: 67
Reputation: 211
@pmkro's answer is good, but if you want to use ES7 async/await instead of Promise.then:
async function doThings() {
const data = await d3.csv('yourcsv.csv');
// do whatever with data here
}
doThings();
Upvotes: 9