0

I would like to get the JSON data from Coinmarket.

I get the data but can't map the Data.

below my Code

    const p = document.querySelector('p');
    let endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
    let coinsdata = [];
    fetch(endpoint)
    .then(blob => blob.json()
    .then(data => coinsdata.push(...data)));

    console.log(coinsdata);
    coinsdata.map(coindata => {
        return p.innerHTML = coindata.id;
    });
  • 1
    also your setting of p.innerHTML is probably incorrect, since you'll just wind up setting probably the same P element repeatedly instead of one for each cryptocurrency – Montagist Dec 05 '17 at 03:45

2 Answers2

1

The issue is you are printing the list straight away, even before the data comes back from the API. You need to set the HTML inside the callback.

const p = document.querySelector('p');
let endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
fetch(endpoint)
  .then(blob => blob.json().then(data => {
    console.log(data);
    coinsdata.map(data => {
      return p.innerHTML = coindata.id;
    });
  })
);
klugjo
  • 19,422
  • 8
  • 57
  • 75
1

The issue with you code is that you have not properly managed the asynchronous xhr call. The code is written outside 'then' code block which is why you are not seeing anything.

The Solution:

let p = document.querySelector('p');
const endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
fetch(endpoint)
    .then(blob => blob.json())
    .then(data => {
        data.map(obj => p.innerHTML += ("\n" + JSON.stringify(obj)) );
    });

This will print the objects in sequence. You can change the code as per your requirement. This was just to show the core idea.

Bharat23
  • 527
  • 3
  • 15