Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember component: A property of X was modified inside the didInsertElement hook deprecation, where should the set go?

Tags:

ember.js

The full deprecation message is DEPRECATION: A property of <orders-app@view:test-holder::ember3010> was modified inside the didInsertElement hook. You should never change properties on components, services or models during didInsertElement because it causes significant performance degradation.

To simplify the scenario lets say we have a component with an input box and we want to set the textbox date to today plus a number of days numberOfDays. So if today is January 3rd 2015 and numberOfDays=2 then the textbox value should be 05-01-2015 (assuming we want DD-MM-YYYY formatting). So our setup could be:

date-shower.hbs

{{input type="text" value=dateInput}}

components/date-shower.js

export default Ember.Component.extend({
  didInsertElement: function() {
    var numberOfDays = this.get('numberOfDays');
    var dayToUse = new Date(); // today
    dayToUse.setDate(dayToUse.getDate() + numberOfDays);

    this.set('dateInput', moment(nextDay).format('DD-MM-YYYY'));
  }
});

We then might use this with something like

{{date-shower numberOfDays=2}}

When it makes sense for a component to calculate the default for one it's properties itself, based off a property passed to it, what hook should I use instead of didInsertElement to prevent the deprecation message?

like image 626
Adam Knights Avatar asked Feb 10 '23 10:02

Adam Knights


1 Answers

I would make dateInput a computed property on the component and let Ember handle setting the property for you to ensure it happens at the right time:

import Ember from 'ember';

const { Component, computed } = Ember;

export default Component.extend({
  didInsertElement() {
    // nothing needed in here
  },

  dateInput: computed('numberOfDays', function() {
    let numberOfDays = this.get('numberOfDays');
    let dayToUse = new Date(); // today

    dayToUse.setDate(dayToUse.getDate() + numberOfDays);

    return moment(nextDay).format('DD-MM-YYYY');
  })
});

This way, your dateInput value will get computed as soon as numberOfDays becomes available.

like image 50
Tom Netzband Avatar answered May 04 '23 00:05

Tom Netzband