Constructor in Lightning Web Component

Constructor in Lightning Web Component is part of the lifecycle hook which is a callback method triggered at a specific phase of a component instance’s lifecycle. Constructor() method fires when a component instance is created.

Constructor in Lightning Web Component flows from parent to child. In simple word, If you have a parent and child component, constructor defined in parent component will get fire first.

What you can do within in a Constructor in Lightning Web Component ?

It is very important to know the limitation of Constructor method in Lightning Web Component . Let’s create a simple Lightning Web Component with name lifeCycle. All lightning web Components has three files in its folder structure by default.

What you can do within in a Constructor Method?

Let’s start with basic syntax of writing constructor method in Lightning Web Component.

import { LightningElement } from 'lwc';

export default class LifeCycle extends LightningElement {
    constructor() {
        super();
        //do something
    }
}

Note:- The first statement must be super() with no parameters. This call establishes the correct prototype chain and value for this. Always call super() before touching this.

Question 1 - Can we set the properties in Constructor() ?

Yes, You can. You can set the value of properties and also can define the variable in it. Example:-

import { LightningElement, track } from 'lwc';

export default class LifeCycle extends LightningElement {
     @track variable;    
     constructor() {
        super();
        //defined a varibale
        let car = "benz";
        if (car) {
            //setting property value
            this.variable = "maruti";
        }
     }
}

Do not use it to set the properties, Use getters and setters instead.

 Question 2 - Can we Access elements the component owns inside the  constructor method in Lightning Web Component?

No, You cannot access the elements inside the constructor. When you try to do that, you will get an error.

//lifeCycle.html
<template>
    <lightning-button label="click here"></lightning-button>
</template>
//lifeCycle.js
import { LightningElement } from 'lwc';

export default class LifeCycle extends LightningElement {
    constructor() {
        super();
        this.template.querySelector('lightning-button');
    }
}
Can we Access elements the component owns inside the  constructor method in Lightning Web Component?
Question 3 - Can we call an apex method inside the constructor method in Lightning Web Component? 

Yes, We can call a apex method inside the constructor. Example:-

//lifeCycle.html
<template>
    <template if:true={contacts}>
        <template for:each={contacts} for:item="contact">
            <p key={contact.Id}>{contact.Name}</p>
        </template>
    </template>
</template>
//lifeCycle.js
import { LightningElement, track } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';

export default class LifeCycle extends LightningElement {
    @track contacts;
    @track error;

    constructor() {
        super();
        getContactList()
            .then(result => {
                this.contacts = result;
                this.error = undefined;
            })
            .catch(error => {
                this.error = error;
                this.contacts = undefined;
            });
    }

}
Can we call an apex method inside the constructor method in Lightning Web Component?
Question 4 - Can we create and dispatch events in constructor method of Lightning Web Component?  

No, You cannot create and dispatch custom events from constructor . If you do so, You will get an error.

import { LightningElement, track } from 'lwc';

export default class LifeCycle extends LightningElement {
    @track contacts;

    constructor() {
        super();
        // Creates the event with the contact ID data.
        const selectedEvent = new CustomEvent('constructorfired', { detail: this.contacts });

        // Dispatches the event.
        this.dispatchEvent(selectedEvent);
    }

}
 Can we create and dispatch events in constructor method of Lightning Web Component?
Question 5 -  Can we call the UI Api from constructor in Lightning web component?

Yes, You can make call to uiRecordApi inside the constructor method in Salesforce. Let’s have a look into sample example:-

import { LightningElement, track } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';

export default class LifeCycle extends LightningElement {
    @track contacts;

    constructor() {
        super();
        const fields = {};
        fields[NAME_FIELD.fieldApiName] = 'account created after from Constructor';
        const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };
        createRecord(recordInput)
            .then(account => {
                console.log('account.id ' + account.id);               
            })
            .catch(error => {
                console.log('error ' + error);     
            });
    }

}
Question 6 -  Can we use navigation service inside the constructor in Lightning Web Component?

Yes, You can not use navigation service inside the constructor.

import { LightningElement, track } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import { NavigationMixin } from 'lightning/navigation';

export default class LifeCycle extends NavigationMixin(LightningElement) {
    @track contacts;

    constructor() {
        super();
        const fields = {};
        fields[NAME_FIELD.fieldApiName] = 'account created after from Constructor';
        const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };
        createRecord(recordInput)
            .then(account => {
                console.log('account.id;' + account.id); 
                this[NavigationMixin.Navigate]({
                    type: 'standard__objectPage',
                    attributes: {
                        objectApiName: 'Case',
                        actionName: 'home'
                    }
                });             
            })
            .catch(error => {
                console.log('account.id;' + error);     
            });
    }

}

Note :- You cannot use navigation service to show toast message because it uses this.dispatchEvent which is not allowed in constructor.

Points to Remember

  • Don’t use a return statement inside the constructor body, unless it is a simple early-return (return or return this).
  • Don’t use the document.write() or document.open() methods.
  • Don’t inspect the element’s attributes and children, because they don’t exist yet.
  • Don’t inspect the element’s public properties, because they’re set after the component is created.
  • Don’t Add Attributes to Host Element During Construction

References

One comment

Leave a Reply