Life Cycle Hooks Vs Connecting An Apex Method To A Function

Scenario: Need to debug and verify if the necessary data is being transmitted from an Apex method to a Web Component.

Possible solution: Create a property, establish a connection to the Apex method, and inspect the property’s value 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));
    }
}

Problem: The Apex method is invoked after all the Life Cycle Hooks, rendering the previous approach ineffective.

Optimized Solution: Wire the Apex method to a function instead of a property. To understand the process, all Life Cycle Hooks are executed first, automatically wiring the Apex method to the function. Within the function, you can log the data returned by the 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);
        }
    }
}

I trust this proves beneficial!