Using Fetch to track Covid Statistics

Alex Spencer
2 min readJan 25, 2021

--

As we come closer to entering our 2nd year of the COVID-19 Pandemic, I'm sure many of us are increasingly wonder how we get the most up-to-date statistics as test positivity rates fluctuate.

There is a readily available API that can be used to track the most important stats: the number of test results, positive tests, negative tests, hospitalizations, and deaths.

I thought it would be useful to breakdown the following API for use in a variety of web applications.

First, we have our arrow function entitled getCovidStats which uses async() and is contained within <script></script> tags. According to MDN, async "enables asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains."

Next, we have a try…catch statement which basically 'tries' or verifies that the statements written after try are valid and function properly. If those statements don't work, an error is thrown by the catch statement. Finally just means that the statements contained within will execute regardless of what happens above.

The syntax for this statement looks like this:

try {
try_statements
}
[catch [(exception_var)] {
catch_statements
}]
[finally {
finally_statements
}]

The const response holds the fetch request to the API. What makes this unique is the await keyword before the fetch. This keyword can ONLY be used with asynchronous functions and is used to wait for a promise. If a given promise is rejected, the await will throw an error.

The finally statement contains the interpolated values from our fetch request and set the innerText to be the newly created markup regardless of what happens above. And lastly, getCovidStats is invoked. This API represents elicits a JSON response to a GET request.

Code courtesy of https://searchengineland.com/coding-for-seo-using-javascript-to-track-covid-19-331209

--

--