3

I'm using Emberfire in my app, and I'm trying to findAll stats, and then sort that model by a key, like in the following example. But, when I sort this way I lose the ability to see real time updates in my template and I have to reload the page to see the new/updated data in the view.

 model() {
    return this.store
      .findAll('stats', {
        reload: true,
        backgroundReload: true
      })
      .then(stats => stats.sortBy('date'));
  }
fentech
  • 310
  • 2
  • 12

1 Answers1

1

You have to define a computed property at your controller or a component, which returns the sorted stats. Do not sort your data at route's model hook. Just return the promise of findAll.

For example:

//controller.js or component.js 
sortedStats: computed('model.@each.date', function() {
  return this.get('model').sortBy('date');
})

Furthermore ember offers a sort macro:

import { sort } from '@ember/object/computed';

By using it you can solve your requirement more elegant:

// ...
this.init() {
  this._super(...arguments);
  this.set('sortDefinition', ['date:asc']);
}
sortedStats: sort('model.@each.date', 'sortDefinition')
// ...
wuarmin
  • 1,848
  • 1
  • 11
  • 24
  • This is perfect. Thank you for this! – fentech Nov 27 '18 at 03:24
  • 1
    Your computed property may should have `model.@each.date` as dependent key. Otherwise it's not invalidated if `date` of an object in `model` changes. You may want to use [`sort`](https://www.emberjs.com/api/ember/3.5/functions/@ember%2Fobject%2Fcomputed/sort) macro. – jelhan Nov 27 '18 at 23:05