1

To brush up on my web development skills I am trying to re-learn API. I got the from this website: https://documenter.getpostman.com/view/10808728/SzS8rjbc?version=latest

In my JS file, I have the following code:

var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};

fetch("https://api.covid19api.com/summary", requestOptions)

  .then(response => response.text())

  .then(result => console.log(result))

  .catch(error => console.log('error', error));

And I see that it logs a lot of data, but I'm not sure how to grab a specific data from the API and display it on the HTML page.

I tried something like this in the JS file:

var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};

fetch("https://api.covid19api.com/summary", requestOptions)

  .then(response => response.text())

  .then(result => console.log(result))

  .catch(error => console.log('error', error));

let tdeaths = data.global.TotalDeaths;

document.getElementById('tdeaths').innerHTML = tdeaths.toLocaleString('en');

But nothing is showing up on my HTML file with

bill.gates
  • 14,145
  • 3
  • 19
  • 47
Nathan Brown
  • 29
  • 1
  • 7

2 Answers2

0

you have to put your code in the .then statement. So it should look like this:

fetch("https://api.covid19api.com/summary", requestOptions)

  .then(response => response.json())

  .then(result => {
   let tdeaths = result.global.TotalDeaths;
   document.getElementById('tdeaths').innerHTML = tdeaths.toLocaleString('en');
   })

  .catch(error => console.log('error', error));
Kris
  • 135
  • 7
0

I see there are two problems.
1. How are you updating data.global.TotalDeaths? it will take the initial value because tdeaths is not getting output from response.
2. The document.getElementByid statement would run before it retrives values from API. so after fixing 1st issue, you should put the statement like below(considering result = data)

.then(result => {
     let tdeaths = result.global.TotalDeaths;
     document.getElementById('tdeaths').innerHTML = tdeaths.toLocaleString('en');
  })
Chandan Kumar
  • 1,066
  • 10
  • 16
  • Thank you! It worked, I'm not sure about question 1? I think you mean how do I have a system of it updating numbers lets say every minute? I don't think I have it yet. How would I do that? – Nathan Brown Jun 19 '20 at 14:16
  • You can set polling the API using this setInterval. https://stackoverflow.com/questions/6835835/jquery-simple-polling-example – Chandan Kumar Jun 19 '20 at 14:25
  • I'm assuming instead of "ajax/test.html" I would replace it with the name of my HTML file, which is index.html, and that this would go on the bottom of the JS page? – Nathan Brown Jun 19 '20 at 17:52