ember-data: findAll() works correctly, query() ... not so much
See original GitHub issueGitHub repository which concicesly recreates this problem:
Below is an explanation of the issue, and the following text also appears in the README of the repo above.
The Core of the Problem
Basically, the bug appears to be centered around the type of query
used in app/routes/index.js
to load the model for the view:
- If I use
.findAll(modelItemName)
- it Works*, however if I do.query(modelItemName, {})
- it Does Not Work*.
What does Works and Does Not Work Mean?
Great question, glad you asked.
First, context: in app/templates/index.hbs
, we have a VERY simple UI:
<button {{action 'addNewItem'}}> + Add New Item </button>
<ul>
{{#each model as |item|}}
<li>{{item.name}}</li>
{{/each}}
</ul>
And the appros router action in app/routes/index.js
does this:
addNewItem() {
let item = this.get('store').createRecord(modelItemName, {
name: new Date()
});
item.save();
}
So, to define the terms Works and Does Not Work:
- Works: (e.g. what happens with
.findAll()
) When clicking the Add New Item button in the UI, triggering theaddNewItem()
action, the new item is automatically rendered in the{{#each}}
block into the page. - Does Not Work: (e.g. what happens with
.query()
): When clicking the button and triggeringaddNewItem()
, the UI never updates. The console shows Mirage POSTed the item and received a valid response (see screenshot below), but the{{#each}}
block is never re-rendered.
No idea how to fix this. Suggestions and/or pointing out the error of my ways is very welcome and desired.
Screenshot
Here’s digital proof showing the console after the Add New Item button was clicked showing that Mirage did post the item but the UI never updated:
Issue Analytics
- State:
- Created 6 years ago
- Reactions:4
- Comments:27 (11 by maintainers)
What you have up there is really close to working. Ember Arrays have two special properties:
[]
, and@each
that you can reference when using an Ember Array as a dependent key in a computed property.In your example, if you want to update and re-sort every time the membership in the list of items changes, you can make sortedItems look like this:
Or, if
item.name
may be updated by something and you want to re-sort when that happens (in addition to when an item is added/removed), you can use.@each
:edit I should add that I didn’t use
[]
or@each
in my previous examples because thefilterBy
computed function sets up the correct observer for you.Sure, if you want a subset of the total available records when this particular route loads you’re free to use
store.query()
in the model hook to get what you need.What would change with that strategy would be to then get a “live”
RecordArray
somewhere other than the model hook. For Example:items
is then a live view into the store and will update whenever a newmodelItemName
gets added.