On this page:

Customize when updates should happen

Customize which property changes should cause an update

Implement shouldUpdate:

shouldUpdate(changedProps) {
  return changedProps.has('prop1');
}

{% include project.html folder="docs/lifecycle/shouldupdate" %}

Customize what constitutes a property change

Specify hasChanged for the property:

static get properties(){ return {
  myProp: {
    type: Number,
    /* Only consider myProp to have changed if newVal > oldVal */
    hasChanged(newVal, oldVal) {
      return newVal > oldVal;
    }
  }
}

{% include project.html folder="docs/lifecycle/haschanged" %}

Manage property changes and updates for object subproperties

Mutations (changes to object subproperties and array items) are not observable. Instead, either rewrite the whole object, or call requestUpdate after a mutation.

// Option 1: Rewrite whole object, triggering an update
this.prop1 = Object.assign({}, this.prop1, { subProp: 'data' });

// Option 2: Mutate a subproperty, then call requestUpdate
this.prop1.subProp = 'data';
this.requestUpdate();

{% include project.html folder="docs/lifecycle/subproperties" %}

Update in response to something that isn't a property change

Call requestUpdate:

// Request an update in response to an event
this.addEventListener('load-complete', async (e) => {
  console.log(e.detail.message);
  console.log(await this.requestUpdate());
});

{% include project.html folder="docs/lifecycle/shouldupdate" %}

Request an update

Request an update regardless of property changes

Call requestUpdate():

this.requestUpdate();

Request an update for a specific property

Call requestUpdate(propName, oldValue):

let oldValue = this.prop1;
this.prop1 = 'new value';
this.requestUpdate('prop1', oldValue);

{% include project.html folder="docs/lifecycle/requestupdate" %}

Respond to an update

Do something after the first update

Implement firstUpdated:

firstUpdated(changedProps) {
  console.log(changedProps.get('prop1'));
}

{% include project.html folder="docs/lifecycle/firstupdated" %}

Do something after every update

Implement updated:

updated(changedProps) {
  console.log(changedProps.get('prop1'));
}

{% include project.html folder="docs/lifecycle/updated" %}

Do something when the element next updates

Await the updateComplete promise:

await updateComplete;
// do stuff
updateComplete.then(() => {
  // do stuff
});

Wait for an element to finish updating

Await the updateComplete promise:

let done = await updateComplete;
updateComplete.then(() => {
  // finished updating
});

{% include project.html folder="docs/lifecycle/updatecomplete" %}