Lit-element: Synchronous update

Created on 9 Nov 2020  路  4Comments  路  Source: Polymer/lit-element

I've got a code like this:

updated(changedProperties) {
        if (changedProperties.has("value")) {
            this.doubledvalue = this.value * 2;
            this.requestUpdate();
        }
    }
}

I want to trigger an update of the template after (and _only_ after) I change this.doubledvalue. It seems, using updated() I update the template twice, asynchronously (update() as well is asynchronous). In my understanding internally lit-element might merge the update requests and perform just one, but also it might not (have I got it right?).
Is there a way to make sure no update is being performed before the change of this.doubledvalue?

docs Core Libraries

Most helpful comment

Looks like this approach needs to be documented at https://lit-element.polymer-project.org/guide/lifecycle#update

BTW, the code snippet above should be changed to use super.update instead of super.

All 4 comments

updated() runs after an update, so any change of a reactive property or call to requestUpdate() will necessarily enqueue another asynchronous update. If you want to compute values _before_ an update, you have to override update() instead, and do the work before super.update(...), like:

update(changedProperties) {
  if (changedProperties.has('value')) {
    this.doubledvalue = this.value * 2;
  }
  super.update(changedProperties);
}

Looks like this approach needs to be documented at https://lit-element.polymer-project.org/guide/lifecycle#update

BTW, the code snippet above should be changed to use super.update instead of super.

I could try it then, all the discussions here about synchronous update (https://github.com/Polymer/lit-element/issues/643, https://github.com/Polymer/lit-element/issues/365, and few others) maybe have misled me.

@arthurevans It does look like we need to update the lifecycle docs to include info about when an update will be triggered. Specifically, we should discuss that derived properties can be computed in update before calling super and this will not trigger an additional update. However, setting properties after super.update or in firstUpdated/updated will trigger an additional update. Maybe this is documented somewhere but it seems reasonable to include in the lifecycle section.

Was this page helpful?
0 / 5 - 0 ratings