javascripttypescriptstatestenciljsstencil-component

Stenciljs @State() not working for Key:Value pairs


I have a Key: Value pair object in my Stenciljs project with the @State() decorator so the components re-render when one or more of the values are updated but the re-rendering does not happen. my object looks like this:

@State() selected: {[key: string]: string} = {x: "", y: "", z: ""};

I update it the following way: this.selected['x'] = newValue;

I know the object is being updated when desired and there are no errors coming up.

Any ideas on how to solve this?

Thank you


Solution

  • Based on Stencil docs:

    mutating an object will not trigger a view update in Stencil, but returning a new copy of the object will

    So you need to treat your selected object as immutable:

    this.selected = {...this.selected, x: newValue};