Hello again! This blog post takes a unique approach as it will continuously receive updates with the latest findings.
I will be sharing best practices and considerations related to LWC, drawing from both Salesforce guidelines and personal experiences.
Let’s begin with the topic of FOR LOOPS.
1- FOR LOOPS
JavaScript ES6 introduces a distinct type of FOR LOOP. (click hereTo delve into the details, ensure that in LWC, you employ a method that does not clash with the LWC architecture.
For instance, if you intend to utilize forEach,
this.lstAccounts.forEach(function(acc){
console.log(acc.Name);
});
Accessing THIS.VARIABLE within this loop will not 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 utilizes THIS. It searches for the value within a loop where the variable is not assigned, resulting in NULL.
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
}
2-Handling Time Fields
The value you receive is in milliseconds, such as “65700000”. It needs to be converted to a time format in JavaScript. I employed the following method to accomplish this.
// 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';
}
3- Binding setInterval
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 prints ‘0’, illustrating the lack of context maintenance. To address this, we bind the context to each anonymous function call.
Simply employ:
.bind(this) // 'this' is the context
Therefore, the JavaScript transforms into:
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 this will prove helpful to you at some point. I’ll continue to update this post with the latest information.
