connectedCallback() in Lightning Web Component

connectedCallback() 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. The connectedCallback() lifecycle hook fires when a component is inserted into the DOM. Use connectedCallback() in Lightning Web Component to understand the state of the “outside” world (a component’s containing environment).

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

What you can do within in a connectedCallback() in Lightning Web Component ?

It is very important to know the limitation of connectedCallback() 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 connectedCallback Method?

Let’s start with basic syntax of writing connectedCallback() method in Lightning Web Component.

import { LightningElement } from 'lwc';

export default class LifeCycle extends LightningElement {
   connectedCallback(){
        //do something
   }    
}
Question 1 - Can we set the properties in connectedCallback() in Lightning Web Component ?

Yes, You can set a property value and also can define the variable. Example:-

import { LightningElement, track } from 'lwc';

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

Do not use connectedCallback() to change the state of a component, such as loading values or setting properties. Use getters and setters instead.

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

You can’t access child elements in the component body because they don’t exist yet. You can access the host element with this.template. Example:-

//lifeCycle.html
<template>
    <div>
        sfbgfn
    </div>
    <lightning-button label="check access"></lightning-button>
    <h1>abcd</h1>
</template>
//lifeCycle.js
import { LightningElement, track } from 'lwc';

export default class LifeCycle extends LightningElement {
    @track variable;   
   connectedCallback(){
        //this.template.querySelector('div');
        console.log(this.template.querySelector('lightning-button'));
        console.log(this.template.querySelector('div'));
        console.log(this.template.querySelector('h1'));
   }    
}
Can we Access elements the component owns inside the   connectedCallback()method in Lightning Web Component?
Question 3 - Can we call an apex method inside the  connectedCallback() method in Lightning Web Component?

Yes, We can call a apex method inside the connectedCallback() in Lightning Web Component. 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;

   connectedCallback(){
        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  connectedCallback() method in Lightning Web Component?
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:-

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

export default class LifeCycle 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 call the UI Api from connectedCallback() in Lightning web component?

Yes, UI Api call is supported inside the conectedCallback(). Let’s see the below example to create a record of account object:

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

export default class LifeCycle extends LightningElement {
   
    connectedCallback(){
        const fields = {};
        fields[NAME_FIELD.fieldApiName] = 'account created after from connectedcallback today';
        const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };
        createRecord(recordInput)
            .then(account => {
                console.log('account.id;' + account.id);
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Account created',
                        variant: 'success',
                    }),
                );
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
            });
   }    
}

Note: Above example also proved the ability to fire a showToastEvent from connectedCallback() method.

ability to fire a showToastEvent from connectedCallback() method

Question 6 – 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 LifeCycle extends NavigationMixin(LightningElement) {
   
    connectedCallback(){
        this[NavigationMixin.Navigate]({
            type: 'standard__namedPage',
            attributes: {
                pageName: 'filePreview'
            },
            state: {
                recordIds: '069B0000006CaNoIAK',
                selectedRecordId: '069B0000006CaNoIAK'
            }
        });
   }    
}
Navigation service will work fine when it is being used inside  connectedCallback() method.

Point To Remember

  • The connectedCallback() hook can fire more than once. 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.
  • Use connectedCallback() to interact with a component’s environment. For Example – Establish communication with the current document or container and coordinate behavior with the environment or Perform initialization tasks, such as fetch data, set up caches, or listen for events (such as publish-subscribe events)

References

3 comments

Leave a Reply