Shreya Shah
Shreya Shah

Reputation: 592

EmberJs deprecate component lifecycle hook didReceiveAttrs

For the Ember version 2.16, they have removed the arguments passed to the didReceiveAttrs component lifecycle hooks. Previously I was getting arguments in the form of an object.

newAttrs:

EmptyObject: 
{
  dataTestId: "test-object"
  items: MutableCell {__MUTABLE_CELL__       [id=__ember1555539649631463096066386]: true, __REF__ [id=__ember1555539649631670217952659]: RootPropertyReference, value: Array(27)}
  prompt: SafeString {string: "Select an Initiator Group"}
  required: true
  selected: MutableCell {__MUTABLE_CELL__ [id=__ember1555539649631463096066386]: true, __REF__ [id=__ember1555539649631670217952659]: RootPropertyReference, value: undefined}
  __proto__: Object
}

After deprecation how to get such an object in the didReceiveAttrs?

Upvotes: 1

Views: 591

Answers (2)

Ember Freak
Ember Freak

Reputation: 12872

There is ember addon which can provide changed attributes,

https://github.com/workmanw/ember-diff-attrs

Shorthand usage:

import diffAttrs from 'ember-diff-attrs';

export default Ember.Component.extend({
  didReceiveAttrs: diffAttrs('email', 'isAdmin', function(changedAttrs, ...args) {
    this._super(...args);

    if(changedAttrs && changedAttrs.email) {
      let oldEmail = changedAttrs.email[0],
          newEmail = changedAttrs.email[1];
      // Do stuff
    }
  })
});

Extended Usage:

import diffAttrs from 'ember-diff-attrs';

export default Ember.Component.extend({
  didReceiveAttrs: diffAttrs({
    keys: ['user', 'isAdmin'],
    isEqual(key, a, b) {
      if (key === 'user') {
        return (a && b) ? a.id === b.id : a === b;
      }
      return a === b;
    },
    hook(changedAttrs, ...args) {
      this._super(...args);

      if(changedAttrs && changedAttrs.user) {
        let oldUser = changedAttrs.user[0],
            newUser = changedAttrs.user[1];
        // Do stuff
      }
    }
  })
});

Upvotes: 0

rinold simon
rinold simon

Reputation: 3052

Uh, this was the Deprecation Added in 2.12. You can get Arguments in Component Lifecycle Hooks until 2.13.0.

An alternative approach for getting the arguments in the hook after 2.13.0 is below,

Before:

didReceiveAttrs({ oldAttrs, newAttrs }) {
  if (oldAttrs.temp !== newAttrs.temp) {
    this.thermometer.move({ from: oldAttrs.temp, to: newAttrs.temp });
  }
}

After:

didReceiveAttrs() {
  let oldTemp = this.get('_oldTemp');
  let newTemp = this.get('temp');

  if (oldTemp && oldTemp !== newTemp) {
    this.thermometer.move({ from: oldTemp, to: newTemp });
  }
  this.set('_oldTemp', newTemp);
}

You can get more info from the official deprecation guide

Upvotes: 2

Related Questions