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?
Yep, that's expected. https://open-wc.org/faq/rerender.html
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.