21

i have a requirement to call a javascript method on load of the template.

is there any way to do that in LWC?

2 Answers 2

26

Replace an init event handler in an Aura component with the standard JavaScript connectedCallback() method in a Lightning web component.

We use the init event in an Aura component to initialize a component after component construction but before rendering.

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

The doInit function in the component's controller performs any necessary initialization.

({
    doInit: function(cmp) {
        // initialize component
    }
})

In a Lightning web component, use connectedCallback() instead in the component's JavaScript file.

// mySampleInit.js
import { LightningElement } from 'lwc';
export default class MySampleInit extends LightningElement {
    connectedCallback() {
        // initialize component
    }
}

Also, read this:- Run Code When a Component Is Inserted or Removed from the DOM


if you are intending to use renderedCallback, You should know that, it will fire after connectedCallback and also it may fire more than once(whenever the component rerender itself).

2
  • thank you for the reply, but my requirement is to call the js method when a component is loaded. i got the answer like we can use renderedCallback() method to do the job done. thank you Commented Apr 15, 2019 at 7:22
  • Based on Migrate Initializers doc Commented Feb 10, 2020 at 20:14
17

To execute actions when component is rendered, use renderedCallback() method and place the required business logic inside this method.

// mySampleInit.js
import { LightningElement } from 'lwc';
export default class MySampleInit extends LightningElement {
    renderedCallback() {
        //  the required business logic to be executed when component is rendered
    }
}
1
  • 4
    if you are intending to use renderedCallback, You should know that, it will fire after connectedCallback and also it may fire more than once(whenever the component rerender itself). Commented Feb 11, 2020 at 14:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .