Search code examples
javascriptstenciljsstencil-component

Executing a method on create for Stencil Components


I am working on a Stenciljs component where an array needs to be filled with fetch calls when the component is created. The array's contents will change throughout the component's life cycle. Right now the only way I can get it to be filled is by having a button that when clicked calls the fill method. How can I fill the array as the component is created or loaded so there is no user interaction required? In other words, how can I call the fill method without a button?

Thank you for your help.


Solution

  • You can use the Lifecycle Methods, in your case componentWillLoad is probably the right one.

    componentWillLoad() {
      this.fill();
    }
    

    You can also return a Promise which will prevent the component from rendering until the Promise is resolved.

    There's also connectedCallback which will be called each time the component is added to the DOM (even if it moves).