0

I want to use Fetch API but I don' t really understand it's mechanism.

I have an <h1> in my HTML and I want to assign the result of my fetch with this code:

const weather = "http://api.apixu.com/v1/current.json?key=cba287f271e44f88a60143926172803&q=Paris";
const array = [];

fetch(weather)
.then(blob => blob.json())
.then(data => {
  array.push(data.current.humidity)
  console.log(array[0])
      }
);
 document.querySelector('h1').innerHTML = array[0]; 

I have the result with the console.log but the <h1> returns "undefined". Can you explain why?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
flenoir
  • 37
  • 6

1 Answers1

2

This is because the call to the API is asynchronous, meaning that the code is not executed just line by line as you write it. The callback only runs as soon as the call to the API has finished, basically meaning that

data => {
  array.push(data.current.humidity)
  console.log(array[0])
}

runs after

document.querySelector('h1').innerHTML = array[0];

So when you try to set your h1, array is still empty. If you want to set it as soon the data is available, you have to do it within the callback function:

data => {
  array.push(data.current.humidity)

  document.querySelector('h1').innerHTML = array[0];
}

This might seem weird at first, but keep in mind that you're only registering an anonymous function but not running it yet. You just define the function that you want to trigger as soon as something happens, in this case: when your API call has finished.

Quasdunk
  • 14,944
  • 3
  • 36
  • 45