Dragos Laic
Dragos Laic

Reputation: 13

How to auto-refresh API DATA?

I'm searching over here how should I refresh my data from api I saw something with setInterval() but I really don't have a clue. Below is what I did its an api for getting stock market data and I would like it to be in real-time without refreshing the page to see it in real time. Firstly is a get which I used to show data on web then post to search it by symbol this is where req.body.stock_ticker is used.

app.get('/stocks.html', function (req, res) {
    call_api( function(doneAPI) {
        res.render('stocks',{
            stock: doneAPI
        });
    },'GOOG');
});

//Set handlebar index POST route.
app.post('/', function (req, res) {
    call_api(function(doneAPI) {
        //posted_stuff = req.body.stock_ticker;
        res.render('stocks',{
            stock: doneAPI,
        });
 }, req.body.stock_ticker);
    
});

//create call_api function
function call_api(finishedAPI, ticker){
//API KEY zzz
    request('https://cloud.iexapis.com/stable/stock/' + ticker + '/quote?token=zzz',{json:true},(err, res,body)=>{
  if(err) {return console.log(err);}
  if(res.statusCode === 200)
  finishedAPI(body);
});
};

Upvotes: 0

Views: 1124

Answers (1)

Noy Gafni
Noy Gafni

Reputation: 1201

If you want to call the api every x milliseconds you need to call the function in setInterval

setInterval(() => {
    call_api(finishedAPI, ticker);
}, <time-in-milliseconds>)

so this code will run call_api(finishedAPI, ticker) every <time-in-milliseconds>

Upvotes: 2

Related Questions