LWC Best Practices & Considerations

451 Views

Hi again! This blog post is going to be a different one as I’ll keep updating this post with all the latest findings.

In this blog post, I am going to share all the best practices and considerations regarding LWC for not just by the Salesforce but even with personal experience.

First, let’s start with FOR LOOP,

1- FOR LOOP

JS ES6 bring a different kind of FOR LOOPS (click here to have a look in details) but in LWC – make sure to use the one which doesn’t conflict with lwc architecture.

For example, if you’re going to use forEach,

this.lstAccounts.forEach(function(acc){
    console.log(acc.Name);
});

You won’t be able to access THIS.VARIABLE inside this loop. Here is a demonstration,

this.lstAccounts.forEach(function(acc){
    console.log(acc.Name);
    console.log(this.someBooleanval); //THIS VALUE WILL BE NULL
});

The reason is that such kind of loop also uses THIS. and looks for the value inside a loop where such variable is not assigned hence – NULL.

SO what should you do ? Use another kind of FOR LOOP – like:

for(let acc of this.lstAccounts){
    console.log(acc.Name);
   console.log(this.someBooleanval); //VALUE WILL BE ACCESSIBLE HERE
}

2- Dealing with Time field

The number you are getting is in milliseconds “65700000”. We need to convert it to time format in js itself. I used the below method to do so.

// 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- setInterval Binding

setInterval runs on different browser subthread thingy… That is it doesn’t maintain the context of what happens after.

Take this code for eg.

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′, which explains the fact that context is not maintained. To make that happen we bind the context to each anonymous function call that is made.

Just use

.bind(this) // 'this' is the context

So the JS 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 hope this will help you at some point – I’ll keep updating this post with latest updates.

Happy Coding!

Leave a Comment