Having some trouble with fetching data to HTML

Having some trouble with fetching data to HTML
0

I am learning ES6, and I am currently learning how to fetch data using API and Json. I had no problems getting the data displayed in the console, but displaying it on an HTML page is causing me a bit of trouble, especially because all the tutorials I have found show different methods.

So far, my code looks like this.

document.getElementById('getRates').addEventListener
('click', getRates);

function getRates(){
fetch ('https://apiv2.bitcoinaverage.com/constants/exchangerates/global')
.then((res) => res.json())
.then((data) => {
    let output = '<h3>Rates</h3>';
    data.forEach(function(rates){
        output += 
    <h3>rate: ${data.rates[rate].name}</h3>
    <h3>rate: ${data.rates[rate].rate}</h3>
    });
    document.getElementById('output').innerHTML = output;
});

I think I am supposed to use constructors, but as I said, the tutorials are only making me more confused.

A friend of mine sent me this suggestion, and I would not mind using it, but I don’t fully understand it, and none of the tutorials I have seen so far has shownn this method.

I hope someone here can help me. Remember, it HAS to be ES6.

Try like this:

document
  .getElementById('getRates')
  .addEventListener('click', getRates);

function getRates() {
  fetch ('https://apiv2.bitcoinaverage.com/constants/exchangerates/global')
    .then((res) => res.json())
    .then(({ rates }) => { // Destructure to select data.rates
      let output = '<h3>Rates</h3>';
      // As rates is an object you have to get keys and iterate over keys
      Object.keys(rates).forEach((rate) => {
        // Use template literals
        output += `
          <h3>rate: ${rates[rate].name}</h3>
          <h3>rate: ${rates[rate].rate}</h3>
        `;
      });
      document.getElementById('output').innerHTML = output;
    });
}

…And don’t try to understand your friend’s code