Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stenciljs @Method not working

I'm struggling to get @Method in stenciljs working - any help would be appreciated.

Here's my component code with a function called setName that I want to expose on my component:

import { Component, Prop, Method, State } from "@stencil/core";

@Component({
  tag: "my-name",
  shadow: true
})
export class MyComponent {

  @Prop() first: string;
  @Prop() last: string;
  @State() dummy: string;

  @Method() setName(first: string, last: string): void {
    this.first = first;
    this.last = last;
    this.dummy = first + last;
  }
  render(): JSX.Element {
    return (
      <div>
        Hello, World! I'm {this.first} {this.last}
      </div>
    );
  }
}

Here's the html and script that references the component:

<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
  <title>Stencil Component Starter</title>
  <script src="/build/mycomponent.js"></script>

</head>
<body>

  <my-name  />

  <script>
    var myName = document.querySelector("my-name");
    myName.setName('Bob', 'Smith');
  </script>
</body>
</html>

Here's a screen shot of the error I'm getting which is Uncaught TypeError: myName.setName is not a function:

enter image description here

like image 798
Carl Rippon Avatar asked May 10 '18 12:05

Carl Rippon


2 Answers

Methods are not immediately available on a component; they have to be loaded/hydrated by Stencil before you can use them.

Components have a componentOnReady function that resolve when the component is ready to be used. So something like:

var myName = document.querySelector("my-name");
myName.componentOnReady().then(() => {
  myName.setName('Bob', 'Smith');
});
like image 137
matthewsteele Avatar answered Nov 17 '22 19:11

matthewsteele


Just posting another answer because this has since changed, with Stencil One.

All @Method decorated methods are now immediately available on the component, but they are required to be async, so that you can immediately call them (and they resolve once the component is ready). The use of componentOnReady for this is now obsolete.

However, you should make sure that the component is already defined in the custom element registry, using the whenDefined method of the custom element registry.

<script>
(async () => {
  await customElements.whenDefined('my-name');

  // the component is registered now, so its methods are immediately available
  const myComp = document.querySelector('my-name');

  if (myComp) {
    await myComp.setName('Bob', 'Smith');
  }
})();
</script>
like image 11
Simon Hänisch Avatar answered Nov 17 '22 19:11

Simon Hänisch