Moshe Kerbel
Moshe Kerbel

Reputation: 131

How to properly handle a prop change with a LitElement component?

My scenario: I have a web component created with LitElement which has an object property. In order to initialise it, i am waiting for the element to get created:

    <script>
      document.addEventListener("DOMContentLoaded", () => {
        const instance = document.querySelector("#myInstance");
        instance.config = {
          data: [
            { firstName: "John", lastName: "Doe", age: 32 },
            { firstName: "Jane", lastName: "Boe", age: 30 },
          ]
        };
      });
    </script>
    <my-component id="myInstance"></my-component>

Let's say that i am going to change this data prop from time to time. I would like to check the value of the data once it is changed and then decide what i should do next. In order to do that, this is the code of my web component:

@customElement("my-component")
export class MyComponent extends LitElement {
  @property({ type: Object }) data: Object;

  protected updated(_changedProperties: Map<PropertyKey, unknown>): void {
    console.log(_changedProperties);
  }

  render() {
      return html`
        <div>blabla</div>
      `;
  }
}

The problem is that _changedProperties map has data but it is still undefined. What am i missing here?

Upvotes: 0

Views: 600

Answers (1)

daKmoR
daKmoR

Reputation: 1864

changedProperties is a Map of all the property names that changed... e.g. you can use it to check what changed - if you want to access the actual value you can use the property directly.

it look like this

if (_changedProperties.has('myProperty')) {
  // react to a myProperty change
  console.log('The new value of myProperty is', this.myProperty);
}

Upvotes: 2

Related Questions