Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

Life Cycle Hooks vs Wiring Apex method to a function

When to use Life Cycle Hooks and wire decorator while debugging in LWC.

By Teja, ex-Salesforce engineer · Updated January 31, 2020 · 1 min read

Scenario - Want to debug and check if required data is being sent from Apex method to Web Component?

Possible solution - Creating a property, wiring it to the apex method and checking the value of the property in one of the Life Cycle Hooks.

// apexWireMethodToProperty.js
import { LightningElement, wire, track } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';

export default class ApexWireMethodToFunction extends LightningElement {

    @wire(getContactList)
    contacts;
    
    connectedCallback() {
        console.log(JSON.stringify(contacts));
    }
    
    renderedCallback(){
        console.log(JSON.stringify(contacts));
    }
}

ApexWireMethodToFunction.js

Problem - Apex method will be invoked after all the Life Cycle Hooks are invoked so the above approach will not be of any help.

Optimised Solution - Wire Apex method to a function instead of a property. If you try to understand what happens here, all the Life Cycle Hooks are invoked and then it will automatically wire the apex method to the function and with in the function you can log the data sent back by apex method.

// apexWireMethodToFunction.js
import { LightningElement, wire, track } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';

export default class ApexWireMethodToFunction extends LightningElement {

    @wire(getContactList)
    wiredContacts({ error, data }) {
        if (data) {
            console.log(data);
        } else if (error) {
            console.log(error);
        }
    }
}

ApexWireMethodToFunction.js

Hope this helps!

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts