connectedCallBack

Lifecycle Hooks of connectedCallback() in LWC

LWC

This diagram shows the flow of the component lifecycle from creation through render.

connectedCallback() Called when the element is inserted into a document. This hook flows from parent to child. You can’t access child elements because they don’t exist yet.

The connectedCallback() hook can fire more than one time. For example, if you remove an element and then insert it into another position, such as when you reorder a list, the hook fires several times. If you want code to run one time, write code to prevent it from running twice.

To check whether a component is connected to the DOM, you can use this.isConnected.

import { LightningElement } from 'lwc';

export default class ConnectedCallBackDemo extends LightningElement {
  connectedCallback(){
        //code here
  }

}

Question 1 – Can we assign value to a variable in connectedCallback() in LWC ?

 

import { LightningElement } from 'lwc';

export default class ConnectedCallBackDemo extends LightningElement {
    flag;   
   connectedCallback(){
         //setting property value
          this.flag= true;
      
   }    

}

Question 2– Is it posible to access component self elements by connectedCallback()method in Lightning Web Component?

We can’t access child elements in body of components because these elements not exist till now.

<template>
	  <p data-id="testA"> Enter the message... </p>
	  <lightning-combobox data-id="testB" name="title" label="Title" value="" placeholder="Select an Option" options={options} required>
                            </lightning-combobox>
	  <lightning-input data-id="testC" type="text" name="firstName" label="First Name" required></lightning-input>
	</template>
import { LightningElement } from 'lwc';

export default class ConnectedCallBackDemo extends LightningElement {
   connectedCallback(){
        const testA = this.template.querySelector('[data-id="testA"]');
        const testB = this.template.querySelector('[data-id="testB"]');
        const testC = this.template.querySelector('[data-id="testC"]');
        console.log('testA==>> '+testA);
        console.log('testB==>> '+testB);
        console.log('testC==>> '+testC);

    }  
}

Result:-
testA==>> null
testB==>> null
testC==>> null

Question 3: – is it possible call apex class method from connectedCallback?

Yes, We can call apex class method from connectedCallback



import { LightningElement } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';


export default class ConnectedCallBackDemo extends LightningElement {
 contacts;
 error;

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

<template>
    <template if:true={contacts}>
        <template for:each={contacts} for:item="contact">
            <p key={contact.Id}>{contact.Name}</p>
        </template>
    </template>
</template>

Question 4 – Can we create and dispatch events in connectedCallback() method of Lightning Web Component?

Yes, it allows you to fire an custom event. Also, you can listen for events (such as publish-subscribe events). Examples:-

import { LightningElement } from 'lwc';
import { registerListener, unregisterAllListeners, fireEvent } from 'c/pubsub';

export default class ConnectedCallBackDemo extends LightningElement {
   
    connectedCallback(){
        // Creates the event with the contact ID data.
        const selectedEvent = new CustomEvent('constructorfired', { detail: this.contacts });

        // Dispatches the event.
        this.dispatchEvent(selectedEvent);
       
        // subscribe to searchKeyChange event
        registerListener('searchKeyChange', this.handleSearchKeyChange, this);
   }    
}

Question 5 – Can we use navigation service inside the connectedCallback() in Lightning Web Component?

Yes, Navigation service will work fine when it is being used inside connectedCallback() method. See the below example to navigate to a file:

import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class ConnectedCallBackDemo extends NavigationMixin(LightningElement) {
   
    connectedCallback(){
        this[NavigationMixin.Navigate]({
            type: 'standard__namedPage',
            attributes: {
                pageName: 'filePreview'
            },
            state: {
                recordIds: '0010K00002h7CYCQA2',
                selectedRecordId: '0010K00002h7CYCQA2'
            }
        });
   }    
}

uniquesymbol

Leave a Reply