Search code examples
ember.jspaginationember-data

Is it possible to store a query in variable?


I'm actually using ember-simple-pagination. It's works with a simple logic : -Empty the sore -Fetch data according to the actual page

The fact is that transition is not smooth at all, see by yourself : https://streamable.com/sg6sg

Is there a way to fix that ? My mind said to me that it would be a solution to fetch data first, empty the sort and then push data back to the store.

import Component from '@ember/component';
import { computed } from '@ember/object';
import { sort } from '@ember/object/computed';
import { inject as service } from '@ember/service';

export default Component.extend({
  store: service(),
  posts: computed(function() {
    return this.get('store').peekAll('post');
  }),

  pageSize: 20,
  pageNumber: null,
  recordCount: null,

  sortProps: ['createdAt:desc'],
  sortedPosts: sort('posts', 'sortProps'),

  loadPosts(getPageNumber) {
    const pageSize = this.get('pageSize');

    this.get('store').unloadAll('post');
    this.get('store').
      query('post', {page: {number: getPageNumber, size: pageSize}}).
      then((result) => {
        this.setProperties({
            'recordCount': result.get('meta.record-count'),
            'pageNumber': getPageNumber
        });
      };
  },

  init() {
    this._super(...arguments);
    this.loadPosts(1);
  },

  actions: {
    getPage(getPageNumber) {
      this.loadPosts(getPageNumber);
    }
  }
});

Solution

  • Ola @elo, thanks for your question!

    It's not currently possible to do that right now with an out-of-the-box solution, but I would recommend looking into loading states for your route so you can show your users a spinner or something while it's loading data. It will make it a little bit less jarring.

    If you want to look at how to set a simple loading state you can follow the guides here: https://guides.emberjs.com/release/routing/loading-and-error-substates/#toc_loading-substates

    There will, of course, be a way to achieve what you want but you will lose some of the functionality of using the store in the first place and one might argue that the user experience might be equally jarring (data doesn't change after you push the button and then suddenly it does). I think using a loading state in your case is the best middle ground 🎉