Home > Enterprise >  Fetch data from API on setInterval without creating another HTML elements
Fetch data from API on setInterval without creating another HTML elements

Time:10-11

My code basically fetches API data, creates HTML elements for each and update the innerHTML elements with API data.

How can I possibly refresh the data from API and update it without creating another HTML elements?

This is my actual code:

let divCrypto = document.getElementById("divCrypto");
let temp, p1, p2, p3, imgz;

let data = [];
const getData = async () => {

for (i = 0; i < 2; i  ){
   coinName = await fetch("https://api.coinlore.net/api/tickers/")
    .then((res) => res.json());
  data.push(coinName.data[i]);
  p1 = document.createElement("p");
  p2 = document.createElement("p");
  p3 = document.createElement("p");
  p1.innerHTML = "Coin:"   " "   data[i].name;
  p2.innerHTML = "Coin:"   " "   data[i].price_usd;
  p3.innerHTML = data[i].percent_change_7d   "%";
  divCrypto.appendChild(p1);
  divCrypto.appendChild(p2);
  divCrypto.appendChild(p3);
  }
console.log(data);
};

getData();
console.log(data);

I tried with : setInterval (getData, 1000); but after each second, it recreates the HTML elements again and again.

I also tried to make 2 different functions but I don't know how to access the data outside the getData() function.

If I console log it outside, after the function is called and the data is updated, I get [] and I cannot understand why.

CodePudding user response:

You can add to the html object the coins you want to display and the function will generate the html for them if it doesn't exist or just update the values if they do exists

let divCrypto = document.getElementById("divCrypto");
let html = { BTC: 1, ETH: 1, ADA: 1 };
let data = [];
let temp, p1, p2, p3, container;
const getData = async () => {
  coinName = await fetch("https://api.coinlore.net/api/tickers/").then((res) =>
    res.json()
  );
  for (i = 0; i < 3; i  ) {
    data.push(coinName.data[i]);
    container = document.getElementById(data[i].symbol);
    if (html[data[i].symbol] && !container) {
      // if this is the first time we read this coin we generate the html
      container = document.createElement("div");
      container.id = data[i].symbol;
      p1 = document.createElement("p");
      p2 = document.createElement("p");
      p3 = document.createElement("p");
      container.appendChild(p1);
      container.appendChild(p2);
      container.appendChild(p3);
      divCrypto.appendChild(container);
    }
    if (html[data[i].symbol]) {
      container.children[0].innerHTML = "Coin:"   " "   data[i].name;
      container.children[1].innerHTML = "Coin:"   " "   data[i].price_usd;
      container.children[2].innerHTML = data[i].percent_change_7d   "%";
    }
  }
  console.log(data);
};
getData();
setInterval(getData, 1000);
//console.log(data);
<div id="divCrypto"></div>

  • Related