ember.js icon indicating copy to clipboard operation
ember.js copied to clipboard

observer / computed property fires twice with queryParams and refreshModel

Open AlexAndBear opened this issue 7 years ago • 1 comments

Ember 3.10.

I am using Ember's queryParameters and refreshModel my queryParameters is an array of objects.
If I change the filters via actions the model gets fired once, but the observers and even the computed properties in the controller fires twice.

I have made a twiddle, so you can reproduce the firing twice observer, unfortunately, the computedProperty bug doesn't appear on twiddle.

https://ember-twiddle.com/7dfa94433ca52197e224c8b58eac6fee

AlexAndBear avatar Jun 15 '19 21:06 AlexAndBear

Hi @devop911,

I ran into a similar issue and found a resolution.

It is not a bug that your computed is firing twice. Rather, Ember is just really fast at computing properties.

Using your Twiddle as an example:

Your filtersComputed will fire twice for the following reasons:

  1. The first time is when you update the filters param using pushObject().
  2. The second time is when the model reloads due to the change in queryParams. Since filters is set on the controller, that property will be updated again during the default setupController portion of the route lifecycle. Since filters is getting reset, filtersComputed will again recompute.

Instead of having your addFilter() action push a new object into filters, consider instead using transitionToRoute(). This will prevent the first unnecessary re-render but still produce the expected result.

Here is what I am envisioning:

actions: {
    addFilter(filter){
        const newFilters = this.get('filters').slice();
        
        newFilters.pushObject(filter);
        
        this.transitionToRoute({ queryParams: { filters: newFilters } });
    }
  }

If you have a component that renders the computedFilters and even has more computed properties or performs actions on them (such as removing), you might run into a scenario where frequent recomputing will cause your component to flicker and re-render. This can be optimized by specifying a key when rendering the array items in in your .hbs.

millerm avatar May 13 '20 20:05 millerm