Search code examples
javascriptfetch-apibinance

Store console.log result into array every 3 second


I am trying to get the price only of bitcoin from Binance for each second and store the result in an array. I have the following code, I have to refresh the page every time I want the last price. I am also not sure how to input that in an array.

var burl ='https://api.binance.com';

var query ='/api/v3/ticker/price';

query += '?symbol=BTCUSDT'; //&interval=15m&limit=2';

var url = burl + query;

var ourRequest = new XMLHttpRequest();

ourRequest.open('GET',url,true);
ourRequest.onload = function(){

  // Will convert the string to something Javascript can understand
  var result = JSON.parse(ourRequest.responseText); 

  // You can now use it as an array
  console.log(result);
}
ourRequest.send();

I also find a fetch method, I am not sure how to adapt this code to help me solve this issue.

componentDidMount() {
    fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
        .then(response => {
            return response.json();
        })
        .then(data => {
            // Here you need to use an temporary array to store NeededInfo only 
            let tmpArray = []
            for (var i = 0; i < data.results.length; i++) {
                tmpArray.push(data.[i])
            }

            this.setState({
                other: tmpArray
            })
        });
} 

Thank you so much!!


Solution

  • To give a request every 3 seconds you need to use setInterval
    To push response price to array you need to use array.push(price)

    let array = [];
    let eachEverySeconds = 3;
    
    function fetchCoinPrice(params) {
      fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
        .then(response => {
            return response.json();
        })
        .then(data => {
            array.push(data.price)
            console.log("tmpArray", array);
        }); 
    }
    
    fetchCoinPrice();
    setInterval(fetchCoinPrice, eachEverySeconds * 1000);