skip to Main Content

I have a function that gets data from a url, then pings the url every x seconds to get the updated data. I am getting data from a fetch(url) then converting the response to a readable json file. Past these two steps are where i am confused. The only method that i am familiar with is for displaying json data is using document.querySelector() to output my fetch(url) data. I semi-understand that my "document.querySelector" is displaying the data in my htmls body, i am just unsure how to export that data from this function to something i can use in a element and style as need be.

let foundationUrl = "https://api.binance.us/api/v3/ticker/price?symbol=";

function createPriceFed(foundationUrl, ticker1, ticker2) {
  var url = foundationUrl + ticker1 + ticker2;
  return url;
}
async function repeatedPinging() {
  var url = createPriceFed(foundationUrl, "BTC", "USD");
  let response = await fetch(url);
  if (response.ok) {
    let json = await response.json();
    if (
      typeof document != "undefined" &&
      typeof document != "[object Object]"
    ) {
      document.querySelector("body").innerHTML =
        json["symbol"] + " : " + json["price"];
    }
  } else {
    alert("HTTP-Error " + response.text);
  }
  setTimeout(repeatedPinging, 8000);
}
repeatedPinging();

I tried displaying my data on my webpage, which works as intended, I am just trying to get that data as a exportable variable i can plug into container elements and style as need be

2

Answers


  1. The way your code is structured (the recursiveness implemented using setTimeout) does not allow you to return anything from that function. In order to get access to the value returned from the API you could define a variable in global scope and assign json to it.

    Login or Signup to reply.
  2. You can create an element in your html and select it with a querySelector in your function, for this case cardBuilder, then you can construct your Html with your data that you get from your api as show in the code snippet below.

    <body><div class="container"></div></body>

    function fetchData(){
            fetch('https://jsonplaceholder.typicode.com/posts')
            .then((res) => res.json())
            .then(data => cardBuilder(data))
            .catch(error => console.log(error.message))
        }
    function cardBuilder(data){
            const container = document.querySelector(".container");
            const generatedData = data.map(post => (`<div>
                    <div><p style="font-weight: bold; color: red;">${post.title</p></div><br>
                    <div>${post.body}</div><br>
                </div>`));
            
            container.innerHTML = generatedData;   
        }
    
        fetchData();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search