Search code examples
ember.jscallbackhandlebars.jscomputed-properties

Ember.js returning to computed property within a callback


I have a computed property that checks if a user has already liked a post:

  likeable: Ember.computed(function () {
    const currentUser = this.get('auth.credentials.id');
    const post = this.get('post.id');

    // Get likes and filter by post and current user

    this.get('store').query('like', {
      filter: {
         user_id: currentUser,
         post_id: post
       }
    }).then(function(like) {

      // Check if any likes were returned

      if (like.get('length') != 0) {
        console.log('length is not 0')
        return false
      } else if (like.get('length') === 0) {
        console.log('length is 0')
        return true
      }
    })
  })

Its being called in my template file like this:

{{#if likeable}}
  <button class="like-button" {{action 'addLike' post}}>Like This Post</button>
{{/if}}

I'm able to see the console.logs and I know the correct records are being retrieved. However, the issue is that the value of likeable is not being updated and the button is never being displayed. I'm pretty sure this is because my conditional is within a callback, and not returning true to the actual computed property. Is there a way around this?


Solution

  • On second thought, I think the likeable property should be defined on your Ember model https://guides.emberjs.com/v2.18.0/object-model/computed-properties-and-aggregate-data/