Refresh model with new params - ember.js

I have a model that calls a query on my store. When something happens that causes the desired model to be a different query, I need to reload the data on the active route by firing the same query just with different param values.
To illustrate, when I come to my items route it fires a query that looks like this
return this.store.query('item',{auction_id: this.get('localStorage.user.user_active_auction'),user_id:this.get('localStorage.user.user_id')}).then((result)=>{
if(result){
return result;
} else {
this.get('notification').notify({message: "An error occurred trying to get items.",success:false});
this.transitionTo('index');
}
});
The localStorage pieces are from a service. When the .user property of the service changes, I need to reload this query with the new .user_active_auction and .user_id values so new data gets placed in the template. (and thusly replaced what was there)
Can't seem to find how to do this as the .refresh() method reloads the cached url it used before rather than creating a new one. Not sure if maybe there is an adapter/serializer method I can implement that will allow me to tell it not to use the cached one?

Related

Ember store.findAll is reloading view and store.query is not

At the moment, when an article is added to the store, my view is not updated when I use store.query(), filtering server side, in my route but it's updated when I use store.findAll() with filtering client side.
With findAll, filtering client side
//route.js
model() {
return this.get('store').findAll('article');
}
//controller.js
articleSorted: computed.filterBy('model', 'isPublished', true),
and with query filtering server side
//route.js
model() {
return this.get('store').query('article', { q: 'isPublished' }),
}
The fact is that findAll is reloading and query is not.
I've found this but did not understand
https://github.com/emberjs/ember.js/issues/15256
thanks for the question. I'll try to answer it the best I can but it would seem like some more documentation should be added to the Ember Guides to explain this situation 🤔
Essentially this.store.findAll() and this.store.query() do two very different things. findAll() is designed to be a representation of all of the entities (articles in your case) so it makes sense that the result will automatically update as the store finds more articles it should care about. It does this because it doesn't return an array of articles, it returns a DS.RecordArray that will automatically update.
query() on the other hand is designed to ask the backend every time what it expects the result to be, and you are usually passing a number of parameters to the query() call that the backend is using to find or filter results. It would be impossible for the frontend to know exactly how the backend interprets these query parameters so it is not possible for it to "auto-update" when a new article is added that would satisfy the same query.
Does that make sense? Would you like me to go into any more detail?
When using store.query to fetch data from the server, the view can still be auto-updated with new client-created store data before it's saved to the server, by using a "live" record array for it.
While data from store.query isn't live, data from store.peekAll is, so you can query first but then leverage store.peekAll for display. You can query before setting your model to the peeked data, or keep your query as the model but use some other property of peeked data for display. The important part is to ensure the query is resolved before peeking at the store.
Example based on the current code in your question:
// route.js
beforeModel() {
// using return ensures this hook waits for the promise to resolve before moving on
return this.store.query('article', { q: 'isPublished' });
}
model() {
// Queried server data should now be available to peek at locally,
// so we can set the model to a live version of it. Don't append filterBy here,
// otherwise it will no longer be live.
return this.store.peekAll('article');
}
// controller.js
// seemingly redundant filter since using query, but needed if there are other records
// in the store that shouldn't be displayed, and is recomputed when
// a record is added or removed from the store-based model
articleSorted: filterBy('model', 'isPublished', true) // filterBy imported from '#ember/object/computed'
// template.hbs
{{#each articleSorted as |article|}}
{{!-- this displayed list should update as new records are added to the store --}}
{{article}}
{{/each}}
Note that after a new record is saved to the server, the query can be updated via its update method or via a route refresh. This will re-run the query and get the updated results from the server. If the query is the model, that would look like model.update(). If it was saved to someOtherProperty, then someOtherProperty.update(). In either case, route.refresh() could be used instead to re-run all route hooks.
Some specific comments/examples that I think are helpful:
https://github.com/emberjs/ember.js/issues/15256#issuecomment-302894768
https://github.com/emberjs/ember.js/issues/15256#issuecomment-302906077
https://github.com/pouchdb-community/ember-pouch/issues/232#issuecomment-428927114

How to re-initialize an ember-data model

In my application, the data in one model is "meta" in nature and defines the attributes in another model. Imagine retrieving a database, where the column definition data determines the attributes of each row.
I can reopen() the row model so long as I have not yet requested rows from the store. A subsequent call to store.findAll('row') retrieves data with all the attributes defined.
If however I have already called store.findAll('row') prior to Column.reopen(), then I cannot find a way cause the store to acknowledge the new attributes.
I have tried without success:
unloading all the rows and finding them again
calling peekAll/update on the rows already in the store
calling Ember.defineProperty() on the row model instead of reopen.
Both existing and subsequent new rows do not get the new attributes.
The solution that works for me is:
let store = this.get('store');
Ember.getOwner(store).unregister('model:item');
Item.reopen(newAttributes);
Ember.getOwner(store).register('model:item', Item);
let currentRoute = this.get('currentRoute');
if (currentRoute) {
currentRoute.refresh();
}
I register the route with the service that updates the schema. When the schema change is detected (which I debounce to avoid thrashing), I unregister the model, update it with reopen, re-register it and refresh the route. There may be a way to get the store to reflect these changes without refreshing the route, but I could not find it.

Updating a model filtered with queryParams without transitioning in EmberJS

In my app I have a route where I'm using queryParams to filter an array.. When I add a new item to the array that matches the filter criteria the template does not update with the new item.
Super simple example bin at http://emberjs.jsbin.com/qetami/1#/colors?type=secondary
In that example, while filtered to Secondary colors click the Add Color button and add a new color with Color Type set to secondary. The color does not immediately appear. If you change the filter then go back to Secondary it appears. It automatically appears when on the unfiltered/default route.
I've tried with and without the queryParams hook in the Colors route with no luck.
This seems like it should be straight forward but I've run into a wall.
I couldn't really get something working with .observes() however I came up with a working version of your example if you leverage actions bubbling up through the routes so that you have a good spot to call this.refresh() in order to reload the filtered model.
http://jsbin.com/qomiba/3/edit
Side-note, I found it confusing that you had references to 'colors' in different places that meant different things.
From emberjs.com/guides
This will offload searching all of the possible records to the server,
while still creating a live updating list that includes records
created and modified on the client.
App.PostsFavoritedRoute = Ember.Route.extend({
model: function() {
var store = this.store;
// Create a filter for all favorited posts that will be displayed in
// the template. Any favorited posts that are already in the store
// will be displayed immediately;
// Kick off a query to the server for all posts that
// the user has favorited. As results from the query are
// returned from the server, they will also begin to appear.
return store.filter('post', { favorited: true }, function(post) {
return post.get('isFavorited');
});
}
});

Update view when pushing models to the store

I have quite a complex page in my application with lots of different models being shown. I live-update several of these models through a /updates REST call. I pass a last_request_timestamp parameter and it returns the models that were created or modified since the last call.
I add the models to the store by using store.push(model, model_json). However, the templates are not updated after the models have been pushed. How can I ensure that there is a binding between the models in the store and the view?
Ok, I figured it out. The Ember.js FAQ says
Filters, on the other hand, perform a live search of all of the records in the store's cache. As soon as a new record is loaded into the store, the filter will check to see if the record matches, and if so, add it to the array of search results. If that array is displayed in a template, it will update automatically.
...
Keep in mind that records will not show up in a filter if the store doesn't know about them. You can ensure that a record is in the store by using the store's push() method.
So in the controller for the view that I want to live-update, I use filter() on the store to fetch the models.
App.PostController = Ember.ObjectController.extend({
comments: function() {
var postId = this.get('id');
return this.get('store').filter('comment', function(comment) {
return comment.get('post.id') == postId;
});
}.property('comments')
});
Now, whenever I push() a new Comment to store, it is automatically added to the appropriate post in the view.
You probably need to explicitly push them into a collection that is being represented on the page by using pushObject. store.push will return a live record, so you could do something like this.
var book_record = store.push('book', model_json);
this.get('controllers.books.content').pushObject(book_record);
That's assuming that the BooksController is a standard ArrayController.
Unfortunately it requires two steps (but simple steps). You need to add it to the store and then save the record for it to propagate changes to listeners via the adapter.
var pushedRecord = store.push(model, model_json);
pushedRecord.save();
Also if you have multiple records you can call pushMany instead of pushing each individually. You still have to save each.
store.pushMany(model, jsonArray).forEach function (pushedInstance) {
pushedInstance.save();
}

Filtered array of local Model records

I have an array controller ActivitiesController which is responsible for managing a days worth of activities (versus the full set). I've set the model property of the ActivitiesRoute to the following:
return this.store.find('activity', {on_date: params.on_date});
This does pull back the appropriate records and I can see them all within the Ember debugger but for some reason these records aren't available to the template (activities.hbs). That was baffling to me but in reality that isn't the final solution anyway (i had just expected it to work).
What I really want to do is have the controller's content manage an array of local Activity records that have been filtered to the specified date. This filtered array then will periodically update based on asynchronous calls to an update query: find('activity', {on_date: this.get('on_date'), since: this.get('since');.
I hope that description makes sense. I've looked at other queries on SO and there were some promising starts but the answers all seemed to be dated and I could find anything that helped me crack this nut.
In summary, I want to:
Have the controller's content be an active filter on the local Activity records that correspond to a given date.
Be able to asynchronously push additional records onto the model which will automagically show on the controller (assuming they're for the appropriate date).
As an aside, I'd be particularly interested to know why my current model hook isn't available the activities template.
------------- UPDATE -------------
I have tried this in my model hook:
return this.store.filter('activity',function(activity){
var itemDate = new Date(activity.get('start_time'));
itemDate = moment(itemDate).format('YYYY-MM-DD');
return itemDate === params.on_date;
});
This should be inline with #Bradley's suggestion. I needed to truncate the time component so I added that logic using the moment.js library. This doesn't throw any errors but also doesn't pull any records from the server by itself so I added the following line of code into the model hook:
this.set('activities', this.store.find('activity', {on_date: params.on_date}));
Using the debugger I can see that the ActivityRoute has an activities property that is set as a DS.PromiseArray and I can see that the activities property has a length of 15 which is the number of activities for that day.
It also looks like the currentModel of ActivityRoute is set to a DS.FilteredRecordArray and it too has the appropriate 15 records in it but my handlebars template still has no ability to iterate over it. I assume this is because the content property of the ActivityController is not set. Why is this step not done by Ember in this situation? Do I need to force this or are there gremlins in the system that need teasing out?
For local filtering you are looking for the DS.Store#filter function.
return this.store.filter('activity', function(activity) {
activity.get('on_date') === params.on_date
});
This returns a DS.FilteredRecordArray that live-updates with new/updated records