New Elements in Array Are Shown at the Bottom and Go to the Top After a Short Delay

Photo of Piotr Pawlik

Piotr Pawlik

Jun 13, 2016 • 2 min read
Ember_app_deployment-1
Let's say you have a list of ordered notes... Model:
sortCreatedAtDesc: ['createdAt:desc'],
notesSorted: Ember.computed.sort('notes', 'sortCreatedAtDesc')

...and they are displayed in a view like this:

[code]

Problem

After adding a new note to the collection, it appears to the bottom of the page, and - after a short delay - moves to the top (where it should appear in the first place as it is the most recent one).

How to make it appear on the top immediately?

Solution

Apparently, it happened because the new note was shown before the information came back from the server. CreatedAt property is set on the backend, so during a short time - when waiting for the backend response - it has the value of null and is placed on the bottom of the page.

The solution to this problem is to sort only the saved notes, omitting those with isNew property.

In model:

sortCreatedAtDesc: ['createdAt:desc'],
notesSaved: Ember.computed.filterBy('notes', 'isNew', false),
notesSorted: Ember.computed.sort('notesSaved', 'sortCreatedAtDesc'),

Keep in mind that there will be a short delay between clicking "Save" and displaying a new note on the list because of it. Therefore, you should consider making UI changes accordingly. For example, you may disable the "Save" button or display the "Note is saving..." message to the user.

Here's an exemplary use of isSaving in save action:

saveNote: function() {
this.set('isSaving', true);
//...
note.save().then(() => {
this.set('isSaving', false);
}
this.set("noteBody", "");
}
Photo of Piotr Pawlik

More posts by this author

Piotr Pawlik

Piotr graduated in Automatic Control and Robotics at the Poznań University of Technology but had...
How to build products fast?  We've just answered the question in our Digital Acceleration Editorial  Sign up to get access

We're Netguru!

At Netguru we specialize in designing, building, shipping and scaling beautiful, usable products with blazing-fast efficiency
Let's talk business!

Trusted by:

  • Vector-5
  • Babbel logo
  • Merc logo
  • Ikea logo
  • Volkswagen logo
  • UBS_Home