Ant
Ant

Reputation: 1163

Reload data in model every X minutes in Emberjs

I'm building a component which takes as an input an IP and returns the error log of that computer. I have setup my model and adapter and they work, but I want to reload the data every few minutes to see if there is a new message.

My component is like this:

import Ember from 'ember';

export default Ember.Component.extend({
  init(){
    this.logMessages = this.get('store').query('log', {ip : this.attrs.ip.value});
    this._super(...arguments);
  },

  didLoad: function(){
    var self = this;
    Ember.run.later(function(){self.logMessages = self.get('store').query('log', {ip : self.attrs.ip.value}); console.log("reload");}, 3000);
  }
});

For some reason I never see the run.later actually running and no errors or warning show up either.

Upvotes: 1

Views: 1070

Answers (2)

Lllama
Lllama

Reputation: 372

I would strongly recommend using ember-concurrency (http://ember-concurrency.com/) for this. You can set a task that runs your store query periodically and have ember-concurrency handle the life-cycle hooks for you. Something like:

pollServerForChanges: task(function * () {
  while (true) {
    yield timeout(2000); // wait 2 seconds
    this.get('store').query(...)
  }
}).on('activate').cancelOn('deactivate').restartable(),

Upvotes: 2

Cory Loken
Cory Loken

Reputation: 1395

You'd want to use a different lifecycle hook. As far as I know there is no didLoad, but you could use didRender, willRender, or didInsertElement based on your exact needs. I'd also remove the timer with one of the destroy hooks otherwise you'll leave timers running when the component is removed. Here is an outline of the lifecycle hooks:

https://guides.emberjs.com/v2.6.0/components/the-component-lifecycle/

Upvotes: 1

Related Questions