Here is the error I am getting on my chrome console. (Access to XMLHttpRequest at ‘file:///…js-bar-chart.js’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
I’m assuming you are opening the html file in your browser and running it locally on your computer. In order to grab a file using fetch you have to be running the html through an actual web server. Do you have a web server installed on your computer? If so, fire it up and then load the page using the server. If not then install one. Or you’ll need to load the page from whatever server you are going to use to host the project.
When I run your code this is the error I get in the console:
TypeError: can't convert undefined to object d3.min.js:3:23819
This may not seem like it helps, but it is telling you that d3 is expecting an object but is getting undefined instead. So basically it’s telling you that d3 doesn’t like what you are passing or is trying to do work on something that isn’t defined yet.
You’ve got a bunch of calls to d3 following the fetch. I don’t know which one is actually complaining about the undefined object but in this case I don’t need to know because I can see where the problem is occurring without having to know anything about d3 (which I don’t).
I can see that dataset plays an important role with d3. You are initializing dataset after you get the json file using fetch. Fetch returns a promise because it may take a while to get that file from the server. When a function returns a promise it basically tells your code to move on with whatever else it needs to do and it will get back to you when it finally has your data. The then methods you tack on to the fetch function are executed when fetch finally has your data. That is when dataset will finally be initialized to the json data. In the meantime, the rest of your code runs as normal, not knowing that you have code waiting for fetch to return.
So while you are waiting for fetch to initialize dataset, all of your calls below to d3 are running and they are using the initial value you set dataset to instead of the json data you are waiting for. So you need to fix your code so that all of the stuff below the fetch function doesn’t execute until after you set dataset to the json data.