Polling Rest API on a Page

Could any one please help as how can we poll a rest API on a page every 5 seconds until a certain condition is met. This is for login with code displayed on TV

You can achieve this using Registry.setInterval() method.

Thanks a lot but how do I use it with the router since my current API calls are done using before in routes

Hi @prashant.chothani . I think you’d need a provide to the return statement of your route hook a Promise, which would then be resolved from inside the setInterval. Then, once resolved, the navigation would proceed as usual.

Hope that helps.

Hi @eduardo.guzman thanks for taking an effort. What i want that on a page i am displaying a Code and then want to poll a service on that page. The user has maps this device (where the lightning app has displayed this code) using the browser or another app. This happens outside of the lightning app. While this is being done, the lighting app where the code is displayed, calls a service, every 5 seconds and then get the bearer token and access token. How do i poll this within the page where the code is displayed. Can i call a function there using Register.setInterval() what you suggested ?

Another way to achieve this is with Rxjs instead of setInterval, which gives you finer control over what is happening and may be better to suit your needs.

import { interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

const destroy$ = new Subject(); 

    switchMap(() => {
      return http.get('/api/messages'); 
  .subscribe(() => {
    // handle the reponse

// later when you want to stop polling

The key points:

  • Use interval to create an observable that emits every 5 seconds
  • Pipe through takeUntil and pass a Subject called destroy$
  • Subscribe to start executing the polling
  • When you want to stop, call next() and complete() on destroy$
  • This will complete the takeUntil and stop the polling

The destroy$ observable is a common pattern for creating a signal to stop observables. Call next() to send a value, and complete() to actually complete the observable.

1 Like
export class Pairing extends Lightning.Component {
  _active() {
    this._interval = setInterval(() => {
      fetch('http://auth.api/status?code=12345').then(response => {
          if (response.status === 200) {
        }, 5000)

  _inactive() {

It’s up to you to build an appropriate UI, add your API configuration, and fetch the pairing code in advance, ofc.
Also this example shows a simplified approach, normally you would need to separate the API communication layer from views and probably add some intermediate state management layer, for example rxjs like @dgmip suggested, or redux, effector, etc.

1 Like