ember-data: findAll() works correctly, query() ... not so much
GitHub repository which concicesly recreates this problem:
- https://github.com/vyalux/ember-list-bug-test
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:

Update: I thought it might be related to .query() somehow not being "live", so I tried using .findAll() with filterBy(), like this, but the filterBy() code is only ran once (as evidenced by console.log statements, not shown). Same results with this code - the addNewItem() action runs correctly, Mirage posts correctly, but the results never show up in the UI.
model() {
return this.store.findAll(modelItemName).then(function(list) {
return list.filterBy("name","test");
});
},
actions: {
addNewItem() {
let item = this.get('store').createRecord(modelItemName, {
name: "test"
});
item.save();
}
}
This seems like a lot of work to get a "reactive" filtered array - even if the array is filtered, it should still re-render when the underlying array is updated, no?
With Knockout, even a computed property which returned an array was re-ran when the underlying observable array that the computed prop used was pushed/popped/etc.
I understand ember is doing a LOT more under the hood than Knockout, as evidenced by the ginormouse API needed to jump thru here - but I'm hoping that all the additional cruft will pay off in a faster, smoother, better, easier app. However, so far, I'm having a heckuva time translating what I "know" into Ember's data model.
Sure, if I just return my own Ember.A array from model(), like: return Ember.ArrayProxy.create({ content: Ember.A([...]) }) - I know that it updates properly.
Would it be better to just make my own utility store that handles the underlying arrays, filters them as needed, and then feeds Ember.A observable arrays out to users as needed, instead of using ember-data?
Bottom line - if I want a "live" list, I'm realizing that model() works great with findAll() - but as soon as I want to apply any sort of client-side filtering (or even pass a query to the server for server side filtering), I loose any semblance of a "live" list.
Please please PLEASE correct me if I'm missing something here or just not translating concepts in my head right - I really want Ember to work for me, just having a hard time getting things to work the way I imagine they should easily and right out of the box.
What you probably want to do is just return the result of findAll() from your model hook, e.g.:
// route.js
model() {
return this.store.findAll(modelItemName);
}
and then leverage a computed property on the controller against the "live" record array you get back from the model hook:
// controller.js
filteredItems: Ember.computed.filterBy('model', 'name', 'test')
and then use that computed property in your template:
// template.hbs
{{#each filteredItems as |item|}}
<li>{{item.name}}</li>
{{/each}}
Hmmm...excellent suggestion. Thanks!
However, this seems to transfer the responsibility for handling the bulk of the filtering onto the individual clients and foregoes the incredibly powerful query engines present on the backend in the form of SQL, etc.
It seems to me that the above suggestion would fall down in the face of tens of thousands of records, etc - when we just really want 100 of those 10,000 records. It seems that it would be better for the server to only send the 100 we need, instead of findAll() giving us 10,000 records then filterBy() finding the relevant 100.
Yes, query() is there for filtering - but the results from query() don't "live" update when records are added or removed from the .store() - and therein lies the crux of the problem: It seems we are at a fork in the road, findAll() and filter yourself and get a live update on Create/Delete ops, or query() and let the server filter, but no live update on Create/Delete ops.
Any way around that quandary? Any way to get the benefits of server filtering with the luxury of the live updating list on the client for create/delete ops?
*Note: In the context of this discussion, when I'm talking about "live updates on Create/Delete ops", I'm talking about Create/Delete ops that happen on the local client, not any sort of streaming sockets or anything - that's another discussion entirely, obviously.
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:
// route.js
model() {
return this.store.query(modelItemName, {/* query */});
}
// controller.js
items: Ember.computed(function () {
return this.store.peekAll(modelItemName);
},
filteredItems: Ember.computed.filterBy('items', 'name', 'test')
items is then a live view into the store and will update whenever a new modelItemName gets added.
Intriguing - I shall test this suggestion - great idea. I'm curious though - this would seem to imply that there could only be one "live view into the store" - e.g. as soon as you query or add items into the store, it would update all "live views."
Yeah, that's not really clear. How about this:
- One list in the UI should be the results of a
query()of records for the model that have Category=A - Another list in the UI should be the results of a
query()of records for the model that have Category=B
It would seem that if we did peekAll() for both lists, they would both get the full list of all model items (e.g. peekAll() would return Category=A items and Category=B items.)
It appears that peekAll() is not tied to a specific query(), it just gives the live view into all the items in the store - so there is only ever one live view of the store (for that model) on the client, is that correct?
Just so I'm thinking correctly, there's no way to get query() to return a "live view" - and that may not be a "bug" but more of a "design decision", is that correct?
Thanks for all your help, by the way!
How would a "live query()" be different than a RecordArray (the result of a findAll() or peekAll()) with a filter applied to it?
Given your scenario above I would think that the following would be satisfactory:
items: Ember.computed(function () {
return this.store.peekAll(modelItemNames);
},
itemsCategoryA: Ember.computed.filterBy('items', 'category', 'a'),
itemsCategoryB: Ember.computed.filterBy('items', 'category', 'b')
Apologies if I overlooked some nuance and that doesn't work.
Ahhh, I see what you're going for - missed that, apologies.
In my thinking, I was imagining the server would be doing the filtering of Category=A and Category=B via the query() call, no explicit filtering needed on the client side.
I apologize, I realize I may be way out of line with all of this. Can I ask how others handle this scenario in the past? I'm sure there are situations in other apps where the entire list of records is larger than you want sent to the client, but you still want the "+ New Item" button to update the UI directly, rather than re-fetching the list from the server? I just don't want to loose sight of the forest for the trees here - I'm open to alternative suggestions to handle that type of a thing, too.
I can envision something where you store a reference to an Ember Array result from query(), and then when the +New Item action is trigger, the controller directly adds the item to the stored Ember Array (and that array, of course, is used in the UI.) Is that what most other apps do? query() the records to get a snapshot of the list, then directly manage adding items to that list instead of relying on the store() to update the list for them?
You would do it exactly as I described above. In the model hook you could query() the backend for any records that are in categories A or B. Now only the records you asked for have been transferred over the wire and are in the local store.
Then you'd set up those two computed properties against a RecordArray that you got from peekAll(). From that point on, any time a new record of that type is added to the store (e.g., by way of store.createRecord()) those computed properties will re-fire and everything will be up-to-date.
Ahhhhhhh, lightbulb there. Got it. So you're suggestion is basically have query() do something like category in ('A','B') (whatever the syntax is) and then do the computed filter in the UI, basically "duplicating" the query, but providing the live array.
I'll have to chew on this for a bit, but I see where you're coming from with that. Thanks for the help!
Drats ... I really wanted it to work like you suggested. But either (a) it's not going to work because the theory is wrong, or (b) my implementation of the theory is wrong. Corrections welcome. Below is what I did, or you can see this code in the repo linked in the OP, https://github.com/vyalux/ember-list-bug-test
Added app/controllers/index.js with the following properties:
items: Ember.computed(function() {
return this.get('store').peekAll(modelItemName);
}),
sortedItems: Ember.computed('items', function() {
console.log("sortedItems computed called...");
return this.get('items').sortBy('name');
}),
Now the index model() hook just does:
return this.get('store').query(modelItemName, {
query: {
$sort: { name: 1 },
}
});
Modified the UI to use sortedItems instead of model:
{{#each sortedItems as |item|}}
<li>{{item.name}}</li>
{{/each}}
The addNewItem action just does:
this.get('store').createRecord(modelItemName, {
name: new Date()
});
item.save();
Problem: The console shows Mirage simulating the POST to the server for the new items, but the sortedItems computed is never re-executed. (The console.log saying sortedItems computed called... only appears once in the console right when the app boots.)
Bottom line: This doesn't appear to work ... the "live array" from peekAll() doesn't appear to notify the computed that it has new items, so sortedItems never re-computes ... or that's what it appears to be doing. Thoughts/suggestions/corrections?
Thanks!
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:
sortedItems: Ember.computed('items.[]', function () {
return this.get('items').sortBy('name');
})
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:
sortedItems: Ember.computed('[email protected]', function () {
return this.get('items').sortBy('name');
})
edit
I should add that I didn't use [] or @each in my previous examples because the filterBy computed function sets up the correct observer for you.
Ahh, how right you are. That did work just as you said!
Okay, I have to ask, because the docs aren't very clear on this matter:
- Can I use multiple properties with @each? Like
items.@each.(name,age)?
Yes, I tried that syntax, didn't work ... thoughts? Or should I chain computed properties?
items.@each.{name,age}
Ahhh ha...bueno.
Am I just blind or missing something in the docs...? My bad for not seeing it if it's there...
@josiahbryan It's documented under the Computed Properties guide, "Multiple Dependents on the same object": https://guides.emberjs.com/v2.13.0/object-model/computed-properties/#toc_multiple-dependents-on-the-same-object.
It's mentioned in the computed properties guide: https://guides.emberjs.com/v2.13.0/object-model/computed-properties/ but not specifically in the section about @each.
And to be honest, I had to actually go and check to see if it worked with @each--it's not something I've ever thought to do.
If either of you has some free time, a PR to https://guides.emberjs.com/v2.13.0/object-model/computed-properties-and-aggregate-data/ adding an example of @each + brace expansion would be appreciated!
Ahhhh thanks @locks and @jaswilli - slowly I'm getting this pieced together. Much appreciation for your patience and help with all of this.
Doing items.@each.{name,age} and then return this.get('items').sortBy('name','age'); in the computed function worked as expected - it reacted properly to changes in both the name and age properties and re-sorted accordingly.
Thanks, @locks, for the suggestion - I'll see if I can whip something up (once I figure out how to do a PR and all that - new to github higher-order concepts like PRs, etc - old dog, new tricks, etc.)
@locks - Where's the source for https://guides.emberjs.com/v2.13.0/object-model/computed-properties-and-aggregate-data/ at? I can't seem to find any files similar in https://github.com/emberjs/website ...?