Wednesday, 2 August 2023

The setters and getters are not called in a custom web component

I have the following web component:

I originally tested this locally, (in a create-react-app) didn't work. I then put it into codesandbox (react template) where it doesn't work either.

class CounterWebComponent extends HTMLElement {
  constructor() {
    console.log("ctor");
    super();
  }

  _count: number = 0;

  set count(value: number) {
    console.log("CounterWebComponent set", value);
    this._count = value;
  }

  get count() {
    console.log("CounterWebComponent get", this._count);
    return this._count;
  }

  connectedCallback() {
    console.log("CounterWebComponent connected");
    this.innerHTML = "<h1>fff</h1>";
  }
  disconnectedCallback() {
    console.log("CounterWebComponent disconnected");
  }
}

if (!customElements.get("counter-wc-custom"))
  customElements.define("counter-wc-custom", CounterWebComponent);

In index.html I'm trying to set the count:

    <counter-wc-custom id="counter1"></counter-wc-custom>
    <script>
      const counter2 = document.getElementById("counter1");
      counter2.count = 23;
      alert(counter2.count);
      alert(counter2._count); //using alert because console.log inside index.html is not working for some reason in codesandbox
      console.log("count", counter2.count); 
      console.log("_count", counter2._count);

      counter2.addEventListener("count", (e) => console.log(e));
    </script>

If I use it like this it works:

const a = document.createElement("counter-wc-custom");
a.count = 2;
console.log("count", a.count);
console.log("_count", a._count);

EDIT: https://codesandbox.io/s/react-web-component-custom-wrapper-xh2n9s (I forgot the link like an idiot)

I assume I configured something somewhere incorrectly but I have no idea what. Any help is appreciated.



from The setters and getters are not called in a custom web component

No comments:

Post a Comment