Calling Apex Methods and Lifecycle Hooks

Calling Apex Methods and Lifecycle Hooks

Calling Apex Methods

In LWC, there are two ways of calling Apex methods:

Imperative Apex: Imperative Apex call is a way to call an Apex method imperatively using JavaScript. This means that instead of relying on the @wire decorator, you can call an Apex method directly from your JavaScript code. In imperative Apex, we explicitly call Apex methods, and the returned value can be used directly in the component.

Here is an example of how to use Imperative Apex in LWC:

import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';

export default class ImperativeMethodCall extends LightningElement {
    contacts;
    error;

    handleClick() {
        getContacts()
            .then(result => {
                this.contacts = result;
            })
            .catch(error => {
                this.error = error;
            });
    }
}

Wire Service: The wire service is a reactive property that keeps your component updated automatically with the latest data from your data source. It uses the @wire decorator to wire an Apex method directly to a property on your component. This method should be used when you need to create a dynamic or real-time response to environmental changes or user actions.

Here's an example of how to use wire service in LWC to call an Apex function:

import { LightningElement, wire } from 'lwc';
import getAccount from '@salesforce/apex/AccountController.getAccount';

export default class WireService extends LightningElement {
    account;
    error;

    @api recordId;

    @wire(getAccount, { accountId: '$recordId' })
    wiredAccount({ error, data }) {
        if (data) {
            this.account = data;
        } else if (error) {
            this.error = error;
        }
    }
}

In the @wire decorator, we pass the Apex method getAccount as the first parameter with any parameters as the second parameter. Any change to the recordId parameter will automatically trigger the wiredAccount method to load the new account data.

So these are the two ways of calling Apex methods in LWC: Imperative Apex and Wire Service.

Lifecycle Hooks

LWC has a unique lifecycle that determines the sequence of events that occur during the component's creation, updates, and destruction. In this blog post, we'll explore the various LWC lifecycle hooks and their significance in building robust and dynamic web applications.

Constructor: The constructor is the first method that gets invoked when the component is created. It is used to initialize the component's state, properties, and other variables. The constructor is an ideal place to set default values for properties or initialize state variables that do not depend on the component's context. Here's an example of how to use the constructor in an LWC component:

import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
  message;
  constructor() {
    super();
    this.message = 'Hello World!';
  }
}

ConnectedCallback: The connectedCallback method is called when the component is added to the DOM. This method is used to perform tasks that require access to the DOM, such as fetching data from an API or initializing third-party libraries. The connectedCallback method is called only once during the component's lifecycle. Here's an example of how to use the connectedCallback method in an LWC component:

import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
  connectedCallback() {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => console.log(data));
  }
}

Render: The render method is responsible for rendering the component's template. It is called whenever the component's state or properties change. The render method must return a template or an array of templates. Here's an example of how to use the render method in an LWC component:

import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
  message = 'Hello World!';

  render() {
    //the below code never works its just an example for render method
    return `
      <div>
        <p>${this.message}</p>
      </div>
    `;
  }
}

RenderedCallback: The renderedCallback method is called after the component's template has been rendered. It is used to perform tasks that require access to the DOM or to manipulate the component's state or properties. The renderedCallback method is called every time the component is rendered. Here's an example of how to use the renderedCallback method in an LWC component:

import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
  message = 'Hello World!';

  renderedCallback() {
    // Perform tasks that require access to the DOM
    const element = this.template.querySelector('p');
    element.style.color = 'red';
  }
}

ErrorCallback: The errorCallback method is called when an error occurs during the component's creation, updates, or destruction. It is used to handle errors gracefully and to prevent the component from crashing. The errorCallback method receives an error object as its parameter. Here's an example of how to use the errorCallback method in an LWC component:

import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
  errorCallback(error) {
    console.error(error);
  }
}

DisconnectedCallback: The disconnectedCallback method is called when the component is removed from the DOM. It is used to perform cleanup tasks, such as removing event listeners or cancelling API requests. The disconnectedCallback method is called only once during the component's lifecycle. Here's an example of how to use the disconnectedCallback method in an LWC component:

import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
  disconnectedCallback() {
    // Perform cleanup tasks
    window.removeEventListener('resize', this.handleResize);
  }
}

Flow Diagram

Conclusion

In this blog post, we explored the various LWC lifecycle hooks and their significance in building robust and dynamic web applications. By understanding the lifecycle of an LWC component, you can write efficient and optimized code that performs well and is easy to maintain.