Lit-element: property type Array, concat

Created on 16 Mar 2020  路  4Comments  路  Source: Polymer/lit-element

When I create a lit-element with a property of type Array (in my case named threads):

  // Element properties
  static get properties(){
    return {
      skip: {type:Number},
      threads: {type:Array},
    }
  }

  // Constructor
  constructor() {
    super()
    this.threads = []
    this._pointer = 0
    this.skip = 1
  }

Then loading new elements and concatinating them to the array does not trigger an update:

  async more() {
    this.threads.concat(await store.list(this._pointer,this.skip))
    this._pointer += this.skip
  }

However when I completely replace the array then the property is updated and the element is rerenderd:

  async more() {
    this.threads = [...this.threads, ...await store.list(this._pointer,this.skip)]
    this._pointer += this.skip
  }

Is this normal behavior, or is something wrong? Am I missing something?

All 4 comments

I see, but isn't this inefficient? Is it possible to push a new element on the array and then trigger the property update manually? Or are Immutable data patterns doing some magic behind the screen to make this efficient?

You can update the array and then call requestUpdate.

As noted by @abraham, there's a nice explanation of how to do an immutable pattern with arrays at https://open-wc.org/faq/rerender.html#litelement-s-property-system. Generally, this is very fast unless extremely high frequency updates are needed, and in that case you can call requestUpdate as also noted by @abraham. Hope that helps.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

erikkroes picture erikkroes  路  3Comments

quentin29200 picture quentin29200  路  3Comments

antonioaltamura picture antonioaltamura  路  4Comments

ghost picture ghost  路  3Comments

zzzgit picture zzzgit  路  4Comments