How To Build a Covid-19 Tracker Using Javascript + Chart.js

Photo by iMattSmart on Unsplash

This has been a really rough year am I right? It wouldn’t be in your best interest to argue with me on that. Even with all the crap that is going on now, lets have some fun with it. Let’s build a COVID 19 tracker for your state/country/providence using Chart.js.

Prerequisites.

A mid-level understanding of HTML, CSS, Javascript, ES6 and using fetch to obtain API data is all you need for this one. I won’t build using a framework since I want this to be novice-friendly.

Creating the project

Directory

Choose any place on your computer and make a folder with the following files included., “index.html, styles.css, script.js”. Or you can also include all of these directly from the HTML like the example below.

Next we are going to get the boilerplate to build out our HTML document. The short cut I am using is from the Bootstrap boilerplate from Visual Studio Code. This isn’t necessary but it will make your life so much easier. You can download many boilerplates from the extensions tab in VS code.

API

The next thing of course would be finding a decent API. The one I love using is Covid Tracking. I enjoy using API’s that have detailed documentation so that I wont have to spend to much time figuring out how to get everything to work.

The only thing you really need is an endpoint, or a url that cotains a query that returns a JSON (Javascript Object Notation) file. JSON is very similar to objects in Javascript but used more specifically for these kinds of scenarios.

Setting up the code (HTML + CSS)

This is basically all that you need. One section with a title (optional) and a container to hold your chart. I have also included the link directly to the CDN for Chart.js and you can also find more information on their website here.

<section> <div class="container-fluid text-center">   <h1 class="h1">Covid Tracker</h1>  <div class="row">   <div class="col-lg text-center chart rounded">   <canvas id="myChart" width="400" height="200"></canvas>  </div> </div></div></section><style>
* {
margin: 0;
padding: 0;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
section {
padding: 8em;
height: auto;
min-height: 100vh;
background-color: white;
color: #d30b0b;
}
.chart {
background: white;
}
</style>
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js'></script>
<script>

</script>

Setting up the code (Javascript)

In your Covid.js file, add these four variables. You don’t have to use the same exact URL as me. I have chosen this one in particular since it would make this tutorial a lot more simpler for novice developers. The covidCases array will hold the positive data from the JSON and the chartLabels array will hold the chart labels obviously.

const chartWrapper = document.querySelector('chart-wrapper');const url = 'https://covidtracking.com/api/v1/us/daily.json';let covidCases = [];let chartLabels = [];

Getting the data

I’m going to use Fetch since it is a perfect and simple way to obtain and read data

fetch(url)
.then(response => response.json())
.then(data => console.log(data)
.catch(err => console.log("Err:" + err + ". Something went wrong")

Fetch is converting the raw data into JSON that can be accessed in the console. Let’s take a look.

{date: 20200717, states: 56, positive: 3626881, negative: 40576852, pending: 3002, …}
1 {date: 20200716, states: 56, positive: 3549648, negative: 39802297, pending: 2929, …}
2 {date: 20200715, states: 56, positive: 3478419, negative: 39042608, pending: 2947, …}
3 {date: 20200714, states: 56, positive: 3413313, negative: 38351244, pending: 960, …}

In the console, since there were no errors (thankfully), we are now able to see the data that has been returned to us. You’ll access these like you would normally do with Javascript objects. For example, if you wanted to know how many positive tests there were on the 14th of July of 2020, you’ll type something like “data[3].positive”.

Next, go inside of the second “.then” block and insert an array variable that will hold you data and another to hold the labels. In this tutorial, I will use the dates as labels for this chart. Normally I wouldn’t make a big deal since you can hover over the chart to see more details on that data but they are required in order for the chart to work properly.

Since we have a lot of data something back from the API, it wouldn’t be wise to manually enter each data object into the array so we will use a forEach function to do that for us.

fetch(url)
.then(response => response.json())
.then(data => {
let covidArray = [];
covidArray.forEach(element => {
chartLables.push(element.date)
covidCases.push(element.positive);
console.log(covidCases)
console.log(chartLables)
});
})
.catch(err => console.log("Err:" + err + ". Something went wrong")

After running this, you’ll be able to see that you arrays look like. They will only consist of the data you want to put into you chart. Now let’s create our chart. I’m going to copy the template from Chart.js.

The only thing that needs our attention is this top part here. I know all the other information can be overwhelming so, this is why I only focus on the details that matter.

All you need to do is create a variable that will place the chart on the canvas you have created in you HTML file earlier. After that has been completed, simply add your arrays with the “reverse()” function. The reason for this is because the data that comes back from the API is in a descending order so reversing it will place it in the ascending order like you’d see in most charts (least to greatest).

var ctx = document.getElementById('myChart').getContext('2d');var myChart = new Chart(ctx, {type: 'line',data: {labels: chartLables.reverse(),datasets: [{label: '# of Votes',data: covidCases.reverse(),

Conclusion

There you have it! For more learning and information, be sure to read my other articles as well.

Full-Stack Developer from Ann Arbor, MI. You’ll always see me on my laptop.