kjb
kjb

Reputation: 3165

Ember-data: Create a record if one does not exist?

I have a computed property where I'm attempting to create a record if one does not exist, but keep getting a jQuery.Deferred exception when attempting to render the computed property.

Here's what I have so far:

deadlineDay: computed(function() {
  const oneWeekFromNow = moment().startOf('day').add(1, 'week');
  const store = this.get('store');

  return store.queryRecord('deadline-day', {
    filter: {
      date: oneWeekFromNow
    }
  }).then(result => {
    if (!result) {
      result = store.createRecord('deadline-day', {
        date: oneWeekFromNow
      });

      result.save();
    }

    return result;
  });
}),

Then in my templates I'm attempting to render with a simple helper:

{{display-date deadlineDay.date}}

The {{display-date}} helper just calls return date.format('dddd, MMM Do')

It looks like Ember is attempting to render the promise itself instead of waiting for it to resolve.

This results in an error since .format is not a method of the promise.

I imagine this is an extremely common use-case, but that I have a lapse in understanding. Much help appreciated!

I'm not sure if it is relevant, but my backing store is sessionStorage via ember-local-storage

Upvotes: 1

Views: 351

Answers (1)

Paul Bishop
Paul Bishop

Reputation: 170

I agree that Ember may be attempting to render the promise itself instead of waiting for the promise to resolve. Unfortunately, I am not able to reproduce the error at this time.

In Ember.js it is typically recommended to place data calls in the route file. This will allow your query/save and all other data gathering to occur prior to the template file being loaded. Your depicted computed property shows no dependent keys, so this may justify moving the calls to the route file for your scenario.

generic route.js example:

import Ember from 'ember';

export default Ember.Route.extend({
  async model() {
    let record;
    record = await this.store.queryRecord('record', { queryParams });

    if (!record) {
        record = this.store.createRecord('record', { properties });
    }

    return record.save();
  },

});

However, if a promise within a computed property is of use, the author of Ember Igniter may have some additional helpful guidance that may be worthwhile. The Guide to Promises in Computed Properties

Upvotes: 2

Related Questions