Wednesday, April 10, 2019

renderedCallback() function/action is getting called multiple times : How to handle?


Hello Guys,


If you have worked on Lightning Web Components and used the renderedCallback() method, you might have seen that it gets called multiple times with one action/operation.

Before going into the issue, first, let's try to understand what exactly
renderedCallback() does. This hook flows from child to parent. When a component rerenders, all the expressions used in the template are reevaluated.

Means all the template variables will be refreshed to get the latest value. Due to mutations, a component is generally rendered multiple times during its lifespan in an application. If you want this action to be called only once and not many times, ummmmm???

Soooo how to handle this?

Do you remember the Apex Trigger and recursion handling? We use the static variable to stop the recursion.

Similar to that, we are going to do it here.

1) Create one private property in your class. In our example its 
isRenderCallbackActionExecuted


import { LightningElement, track, api } from 'lwc';
export default class RenderCallBackExample extends LightningElement {

isRenderCallbackActionExecuted = false;


2) In your renderedCallback method add the following lines. What will these couple of lines do?
It will check if the action has been already executed, by checking if the flag is set. If it's true it will skip the execution and our function will be called only once.

renderedCallback() {
        if (this.isRenderCallbackActionExecuted)) {
            return;
        }

        this.isRenderCallbackActionExecuted = true;
        // Method action implementation.
}

Now, you might ask, this is the solution for executing it only once, what if I want this to be called once, on a particular action such as button click or anything. It's simple. Just reset the isRenderCallbackActionExecuted flag to false again. So next time method will execute once again.

Example: Following code is the snippet for Search box text change.


handleKeyChange(event) {

        if (this.searchKey !== event.target.value) {
            this.isRenderCallbackActionExecuted = false;
            this.searchKey = event.target.value;
        }

}


I hope you enjoyed the learning, please write me back the suggestions, comments or any issues. Let's meet in our next blog with more learnings and fun. :)


THANK YOU!

2 comments:

Salesforce: Export to Excel with Lightning Web Component

Hello Guys, I hope you are doing well. In this post, we are going to see an implementation of " Export to Excel" in lightn...