# Computed properties: What am I missing?

**URL:** <https://discuss.emberjs.com/t/computed-properties-what-am-i-missing/19069>\
**Category:** General\
**Created:** [August 17, 2021, 9:56am UTC](https://discuss.emberjs.com/t/computed-properties-what-am-i-missing/19069 "2021-08-17T09:56:12Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![nclspal](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/nclspal/32/17503_2.png) [@nclspal](https://discuss.emberjs.com/u/nclspal)\
**Post date:** [August 17, 2021, 9:56am UTC](https://discuss.emberjs.com/t/computed-properties-what-am-i-missing/19069/1 "2021-08-17T09:56:12Z")

</div>

Hi,

The behavior of ember computed properties always suprises me and I would like to have a better understand of it. (_I am using **Ember 3.4** )_

Lets say I have two really simple models: a user model and a subscription model. The user **has many** subscriptions and a subscription always **belongs to** a user. The state of a subscription represents whether it is active or not.

Models are defined like so:

```auto
# models/subscription.js
import DS from 'ember-data';
import { computed } from '@ember/object';

export default DS.Model.extend({
  user: DS.belongsTo('user'),
  state: DS.attr('string'),

  isActive: computed('state', function() {
    return this.get('state') == "active";
  })
})

```

```auto
# models/user.js
export default DS.Model.extend({
  ...
  subscriptions: DS.hasMany('subscription'),
});

```

Now lets say I want to know if the user has an active subscription: Should be easy, I just have to create a computed property of the user for this:

```auto
hasAnActiveSubscription: computed('subscriptions.@each.state', function() {
  this.subscriptions.forEach(subscription => {
    if (subscription.isActive)
      return true;
  })
  return false;
})

```

Making sure the subscriptions states are loaded using the computed dependence key, then looping through the subscriptions   
But this does not work and I can’t seem to get why ?

So I’ve added some debug logs and I inspected my models data with the **Ember Inspector** :

```auto
hasAnActiveSubscription: computed('subscriptions.@each.state', function() {
  this.subscriptions.forEach(subscription => {
    console.log(`Subscription [${subscription.id}] has state: ${subscription.state} - (isActive: ${subscription.isActive})`)
    if (subscription.isActive)
      return true;
  })
  return false;
})

```

Which gives the following output:

```auto
user.js:74 Subscription [1] state: undefined - (isActive: false)
user.js:74 Subscription [1] state: active - (isActive: true)

```

I can assume to first output is due to a call to the property when the subscriptions have not been fully loaded and the second call is triggered because the subscriptions array have changed and the property needs to be recomputed but I am not quite sure.

What I am sure is that the following solution fixes the problem and I can’t understand what more it is doing under the hood to make it working as expected:

```auto
hasAnActiveSubscription: computed('subscriptions.@each.state', function() {
  const activeSubscription = this.subscriptions.findBy('state', 'active')
  return activeSubscription !== undefined
})

```

I’m pretty sure I am missing something on computed property as I always face problems like that when property are not properly computed. Is there anything obviously wrong with the first code sample I provided ? What makes it wrong ?

---

<div class="post-metadata">

**Author:** ![dknutsen](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/dknutsen/32/16471_2.png) [@dknutsen](https://discuss.emberjs.com/u/dknutsen)\
**Post date:** [August 17, 2021, 8:24pm UTC](https://discuss.emberjs.com/t/computed-properties-what-am-i-missing/19069/2 "2021-08-17T20:24:33Z")

</div>

> [@nclspal](#):
>
> ```auto
> this.subscriptions.forEach(subscription => {
> if (subscription.isActive)
> return true;
> })
> 
> ```

I think part of the problem is that code isn’t “correct” in the sense that it’s not going to do what you expect. A forEach doesn’t do anything with the return value of each iteration so this CP as written would always loop through all of the subscriptions and then always return false. I think using `this.subscriptions.any` would make more sense and give you the correct result.

That said your second example is a little more idiomatic:

```auto
hasAnActiveSubscription: computed('subscriptions.@each.state', function() {
  const activeSubscription = this.subscriptions.findBy('state', 'active');
  return !!activeSubscription;
})

```

Additionally, one thing that may help to avoid situations like this in the future is using one or more of the computed macros instead of custom CPs (there are a bunch of options, but something like this):

```auto
  activeSubscriptions: filterBy('subscriptions', 'state', 'active'),
  hasAnActiveSubscription: notEmpty('activeSubscriptions')

```

---

<div class="post-metadata">

**Author:** ![dknutsen](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/dknutsen/32/16471_2.png) [@dknutsen](https://discuss.emberjs.com/u/dknutsen)\
**Post date:** [August 17, 2021, 8:28pm UTC](https://discuss.emberjs.com/t/computed-properties-what-am-i-missing/19069/3 "2021-08-17T20:28:16Z")

</div>

> [@nclspal](#):
>
> I can assume to first output is due to a call to the property when the subscriptions have not been fully loaded and the second call is triggered because the subscriptions array have changed and the property needs to be recomputed but I am not quite sure.

Also forgot to mention: this is correct. The CP is calculated once before the subscriptions have finished loading and again once they have resolved. This is necessary when working with computed data based on async data.

---

<div class="post-metadata">

**Author:** ![nclspal](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.emberjs.com/nclspal/32/17503_2.png) [@nclspal](https://discuss.emberjs.com/u/nclspal)\
**Post date:** [August 18, 2021, 6:31am UTC](https://discuss.emberjs.com/t/computed-properties-what-am-i-missing/19069/4 "2021-08-18T06:31:36Z")

</div>

> [@dknutsen](#):
>
> I think part of the problem is that code isn’t “correct” in the sense that it’s not going to do what you expect. A forEach doesn’t do anything with the return value of each iteration

Oh wow, I should have known better… Thanks for correcting such a mistake. I am not used to a `return` not breaking loops iterations or code blocks but that’s really good to keep in mind for this particular method.

> [@dknutsen](#):
>
> Additionally, one thing that may help to avoid situations like this in the future is using one or more of the computed macros instead of custom CPs (there are a bunch of options, but something like this):
> 
> ```auto
> activeSubscriptions: filterBy('subscriptions', 'state', 'active'),
> hasAnActiveSubscription: notEmpty('activeSubscriptions')
> 
> ```

This is one thing that I will be watching very closely from now on as it seems it can make my life easier. I often find myself doing _over_complicated CPs while maybe I could just split it into several macro bits to reach the end result.

Thanks a lot for your help and tips
