RonPringadi
RonPringadi

Reputation: 1494

How to do polling in Ember js component?

In ember js 3.24 LTS, I can create a component that receive data from an API call inside a route. The data from the API is an activity logs. The complexity arrives when I try to keep updating the logs with the latest logs, I need to keep polling the API every few seconds and I need to keep updating the data that being displayed inside the component.

This component gets data from an API call which is in the routes.

// addon/routes/single-scan/index.js 
import { later } from '@ember/runloop';
...
  async model() {
    let phaseActivityLog = await this.pollTestActivity(testId);
    return { phaseActivityLog };
  }

  async pollTestActivity(testId) {
    later(
      this,
      function () {
        this.pollTestActivity(testId);
      },
      2000
    );
    let phaseActivityLog = await this.store.query('phase-activity-log', testId, { reload: true }); // poll this
    return phaseActivityLog;
  }

And my component hbs

// components/single-scan/phase-activity-log.hbs

{{#each @phaseActivityLog as |row|}}
  {{row.timeStamp}} - {{row.event}} - {{row.userName}}
{{/each}}

Upvotes: 0

Views: 325

Answers (1)

Rabbi hasan
Rabbi hasan

Reputation: 360

In controller Initialize @tracked variable and set phaseActivityLog on this @tracked variable after query promise is finished. Then pass this @tracked variable in component as an argument.

If You use @tracked decorator when @tracked variable value change its render automatically.

// addon/controllers/single-scan/index.js 

import { tracked } from '@glimmer/tracking';

@tracked phaseActivityLog = null;

async pollTestActivity(testId) {
later(
  this,
  function () {
    this.pollTestActivity(testId);
  },
  2000
);
 await this.store.query('phase-activity-log', testId, { reload: true 
 }).then(result=>{
  this.phaseActivityLog = result;
 }); 

}


// components/single-scan/phase-activity-log.hbs

{{#each @phaseActivityLog as |row|}}
 {{row.timeStamp}} - {{row.event}} - {{row.userName}}
{{/each}}

Upvotes: 1

Related Questions