10

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

is there any way to do that in LWC?

13

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).

  • 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 – sandeep ch Apr 15 '19 at 7:22
  • Based on Migrate Initializers doc – Brian Miller Feb 10 at 20:14
4

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
    This is the correct answer. The upvoted answer from sanket is incorrect IMHO. – Phil W Dec 18 '19 at 15:54
  • 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). – sanket kumar Feb 11 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.