Refreshing Application Data when switching routes

#1

I have a multi-user ember application where the back-end (REST API) keeps track of progress of the entire team. So, I have done the following:

adapters/application.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  namespace: 'cws/api',
  host: '..',
});

routes/application.js

import Route from '@ember/routing/route';

export default Route.extend({
  model() {
    return Ember.RSVP.hash({
      currentProgress: this.store.findRecord('progress', 1, {reload: true})
    });
  }
});

templates/application.hbs

<div>{{model.currentProgress.percentage}}%</div>

Whenever someone switches routes, I’d like to refresh the model.currentProgress value. I tried doing that by adding a refresh() or reload() to all the other routes’ js files, but that causes an infinite loop.

How would you do this?

0 Likes

#2

You should be able to use willTransition in the route to do this. Here’s an example twiddle which uses the willTransition hook on the application route and a provider-component to emulate the behaviour you’re after.

0 Likes

#3

Wow - this was unbelievably easy!

Thank you so much!

1 Like

#4

Actually, I now see the REST call made twice per route.

application.js

import Route from '@ember/routing/route';

export default Route.extend({
  model() {
    return Ember.RSVP.hash({
      currentProgress: this.store.findRecord('progress', 1, {reload: true})
    });
  },
  actions: {
    willTransition() {
      this.refresh();
    }
  }
});
0 Likes

#5

Are you just using the willTransition hook on the application route?

These events will bubble from the closest route all the way up. For instance if your route is foo.bar.something then the willTranstion of something will be called first, then bar, then foo. So if you want all routes under foo.bar.* to retrieve the progress then you should put the function in routes/foo/bar.js and only there.

0 Likes