javascript - Polling API every x seconds with react - Stack Overflow

PHOTO EMBED

Sun Jan 02 2022 17:51:22 GMT+0000 (Coordinated Universal Time)

Saved by @longshot #javascript

let apiTimeout = setTimeout(fetchAPIData, 1000);

function fetchAPIData(){
    fetch('API_END_POINT')
    .then(res => {
            if(res.statusCode == 200){
                // Process the response and update the view.
                // Recreate a setTimeout API call which will be fired after 1 second.
                apiTimeout = setTimeout(fetchAPIData, 1000);
            }else{
                clearTimeout(apiTimeout);
                // Failure case. If required, alert the user.
            }
    })
    .fail(function(){
         clearTimeout(apiTimeout);
         // Failure case. If required, alert the user.
    });
}
content_copyCOPY

https://stackoverflow.com/questions/46140764/polling-api-every-x-seconds-with-react/63134447#63134447