Life Cycle Hooks In Lightning Web Component | Salesforce Lightning

Lightning Web Components

Now we can build Lightning components using two programming models: Lightning Web Components, and the original model, Aura Components. Lightning web components are custom HTML elements built using HTML and modern JavaScript. Lightning web components and Aura components can coexist and interoperate on a page. To admins and end users, they both appear as Lightning components.

LWC Lifecycle Hooks

Component Life Cycle:

  1. Constructor() 
  2. ConnectedCallback() 
  3. DisConnectedCallback() 
  4. RenderedCallback() 
  5. ErrorCallback() 

1. Constructor

  • We can set the properties in constructor(). 
  • You cannot access the element inside the constructor. 
  • We can call an apex method inside the constructor method. 
  • You can’t make and dispatch custom occasions from constructor. 
  • You can make all to uiRecordApi inside the constructor method in Salesforce. 
  • You cannot use the navigation service inside the constructor. 

Syntax:

constructor(){ 
    super(); 
    //Do something 
} ;

Example: 

constructorDemo.html 

<template> 
<div>Constructor -Demo</div> 
</template>

constructorDemo.js 

import { LightningElement } from 'lwc'; 
export default class ConstructorDemo extends LightningElement { 
    constructor() { 
        super(); 
        this.classList.add('new-class'); 
        console.log('In Constructor'); 
    } 
}

Output – Constructor -Demo 

Don’t forget to check out: QRCode with LWC in Salesforce

2. ConnectedCallback() 

  • The connectedCallback() lifecycle snare fires when a part is embedded into the DOM. 
  • This hooks flow from parent to child. You can not access child elements from the callback because they don’t exit yet. 
  • The connectedCallback() snare can fire more than one time. 
  • You can set the properties and also can define the variable. 
  • You can’t access child element in the component body because they don’t exit yet. 
  • You can call an apex method inside the connectedCallback() method. 
  • You can create and dispatch custom events from method. 
  • You can make call to uiRecordApi inside the method Salesforce. 
  • Subscribe and unsubscribe from a message. 

Syntax:

import { LightningElement } from 'lwc';  
export default class LifeCycle extends LightningElement {  
    connectedCallback(){ 
        //do something 
    } 
}

Example: 

ConnectedCallbackClass 

public with sharing class ConnectedCallbackClass 

{ 
    @AuraEnabled(cacheable=true) 
    public static List<Account>  getAccountList(){ 
        return [SELECT Id, Name,Phone,Industry FROM Account order by createddate desc LIMIT 5]; 
    } 
}

ConnectedCallbackDemo.html 

<template> 
    <template if:true={isSpinner}> 
        <div class="spinner"> 
            <lightning-spinner alternative-text="Loading" size="medium"></lightning-spinner> 
        </div> 
    </template> 
    <lightning-card title="connectedCallback Example"> 
        <lightning-datatable data={accountList} columns={cols} key-field="Id"> 
        </lightning-datatable> 
    </lightning-card> 
</template>

Example: 

ConnectedCallbackDemo.js 

import { LightningElement, wire, track } from 'lwc'; 
import getLatestAccounts from '@salesforce/apex/ ConnectedCallbackClass.getAccountList'; 
const COLS = [ 
    { label: 'Name', fieldName: 'Name', type: 'text' }, 
    { label: 'Stage', fieldName: 'Phone', type: 'text' }, 
    { label: 'Amount', fieldName: 'Industry', type: 'text' } 
]; 
export default class ConnectedCallbackLwc extends LightningElement { 
    cols = COLS; 
    @track isSpinner = false; 
    @track accountList = []; 
    connectedCallback() { 
        this.isSpinner = true; 
    } 
    @wire(getLatestAccounts) fetchAccList(result) { 
        this.isSpinner = false; 
        if (result.data) { 
            this.accountList = result.data; 
            this.error = undefined; 
        } else if (result.error) { 
            this.error = result.error; 
            this.accountList = []; 
        } 
    } 
}

3. DisconnectedCallback()

  • The disconnectedCallback() lifecycle hook fires when component is removed from th DOM. 
  • This hooks flow from parent to child .you cn access child elements from callback because they don’t exit yet. 
  • Use disconnectedCallback() to clean up work done in the connectedCallback(), like pursing caches or removing event listeners. 

Syntax:

import { LightningElement } from 'lwc';  
export default class LifeCycle extends LightningElement {  
    disconnectedCallback(){ 
        //do something 
    } 
}

dont miss out iconCheck out another amazing blog by Narendra here: Apex Test Class in Salesforce – Learn All About It

4. RenderedCallback()

  • the renderedCallback()is unique to lightning web components. Use it to perform rationale after a part has completed the delivering stage. 
  • This hook flows from child to parent if you are dealing with nested parent-child component renderedCallback() method in the child component will get fired first. 
  • You can set the properties but use getters and setters instead.
  • You can access the element owned by component. 
  • You can call an apex method insisde the renderedCallback method. 
  • You can create and dispatch custom events from metod. 
  • You can make call to uiRecordApi inside the method salesforce. 

Syntax:

import { LightningElement } from 'lwc'; export default class RenderedCallbackInLWC extends LightningElement {  
    renderedCallback() { 
        //do something 
    }  
}

5. ErrorCallback()

  • implement it to create an error boundary component that captures errors in all the descendent components in its tree. 
  • It captures errors that occur in the descendant lifecycle hooks or during an event handler declared in an HTML template. 
  • The error argument is a javascript native error object and the stack argument is a string. 

Syntax:

error; 
stack; 
errorCallback(error,stack){ 
    this.error=error; 
}

 



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *