Hello again! This blog post will be unique as I will continuously update it with the latest discoveries.
In this blog post, I will discuss best practices and considerations related to LWC, drawing from my experience both with Salesforce and personally.
Let’s begin with the topic of FOR LOOPS.
- FOR LOOPS
JavaScript ES6 introduced various types of FOR LOOPS (you can explore them in detail here), but when working with LWC, it’s important to use one that doesn’t conflict with the LWC architecture.
For instance, if you intend to use forEach,
this.lstAccounts.forEach(function(acc){ console.log(acc.Name); });
Within this loop, accessing THIS.VARIABLE won’t be possible. Here’s an illustration:
this.lstAccounts.forEach(function(acc){ console.log(acc.Name); console.log(this.someBooleanval); //THIS VALUE WILL BE NULL });
This occurs because this type of loop also employs this
and attempts to locate the value within a loop where such a variable is not assigned, resulting in a NULL value.
So, what’s the solution? Opt for a different type of FOR LOOP, such as:
for(let acc of this.lstAccounts){ console.log(acc.Name); console.log(this.someBooleanval); //VALUE WILL BE ACCESSIBLE HERE }
- Handling Time Fields
The value you receive is in milliseconds, such as “65700000.” To convert it to a time format in JavaScript, you can employ the following method that I utilized:
// Convert milliseconds into 'h:mm a' time format msToTime(s){ let ms = s % 1000; s = (s - ms) / 1000; let secs = s % 60; s = (s - secs) / 60; let mins = s % 60; let hrs = (s - mins) / 60; hrs = hrs < 10 ? '0' + hrs : hrs; mins = mins < 10 ? '0' + mins : mins; console.log(hrs + ' ' + mins); return hrs+':' + mins + ':00.000Z'; }
- Binding for setInterval
setInterval
runs on a separate browser subthread, which means it doesn’t retain the context of what happens afterward.
Consider this code, for example:
var count = 0; var intervalID = setInterval(function (){ this.count++; console.log(this.count); // prints number from 0 to percentage if (this.count === this.percentage) { clearInterval(intervalID); } },10) console.log(this.count); // prints 0
The second console output shows ‘0’, illustrating the lack of context preservation. To address this, we need to bind the context to each anonymous function call. You can achieve this by simply using:
.bind(this) // 'this' is the context
Therefore, the JavaScript code becomes:
import { LightningElement, track } from 'lwc'; export default class App extends LightningElement { @track count = 0; @track percentage = 99; connectedCallback() { var intervalID = setInterval(function (){ this.count++; if (this.count === this.percentage) { clearInterval(intervalID); } }.bind(this),10); } }
I trust that this information will be valuable to you in the future. I’ll continue to enhance and update this post with the latest insights.
Happy coding!