0

I once wrote a very simple code to fetch&display data from certain api. Now that that API doesn't work anymore, I wanted to keep the code intact and make it display an error message that the API doesn't work.

async function getInfected() {
  const api_url = //API Address that doesn't work anymore//;
  const response = await fetch(api_url);
  // console.log(response);
  if (response.ok){
    const data = await response.json();
    const todayInfected = data.data[0][3];
    const todayDeath = data.data[0][2];
    document.getElementById('todayInfected').textContent = todayInfected;
    document.getElementById('todayDeath').textContent = todayDeath;
  } else {
    const errorMessage = "Error! Can't fetch API!";
    document.getElementsByClassName('nowp').textContent = errorMessage;
  }
}

getInfected();

This code does nothing and console.log(response) also doesn't work. And unfortunately, I have very little understanding of fetch(). Any Ideas?

  • 1
    use try/catch to catch the error at `fetch()` - then you'll be able to see what the error is – Jaromanda X May 21 '20 at 10:46
  • This is unrelated to `fetch`. `document.getElementsByClassName('nowp')` doesn’t have a `textContent` property. Please try using the [debugging capabilities](https://developer.mozilla.org/en-US/docs/Mozilla/Debugging/Debugging_JavaScript) of your browser. This is not a lot of code, so you should be able to pinpoint the issue: to a single line of code: `document.getElementsByClassName('nowp').textContent = "Some text";`. – Sebastian Simon May 21 '20 at 10:47
  • Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Sebastian Simon May 21 '20 at 10:47
  • 1
    If the API doesn't work any more, you won't get a `response` at all, and not a response that's not ok either. You'll get an error when trying to connect instead. – Bergi May 21 '20 at 10:48

0 Answers0