Friday, March 11, 2022

How to use variable in Wire method in Lightning Web Component


The wire service provisions an immutable stream of data to the component. Each value in the
 stream is a newer version of the value that precedes it.

We call the wire service reactive in part because it supports reactive variables, which
 are prefixed with $. If a reactive variable changes, the wire service provisions new data. 

Use '$variableName' while calling wire method instead of using this.variableName. 
This will avoid the undefined variable issue while calling Wire method in Salesforce.

Check the following sample code. '$recordId' will not throw any error. But, if this.recordIdis used, it will throw 
undefined exception. 

import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

export default class Record extends LightningElement {
    @api recordId;

    @wire(getRecord, { recordId: '$recordId', fields: ['Account.Name'] })
    record;
}

Some of Useful JavaScript's methods in LWC and Lightning Component

 Hello Friends ,today we are going  to discuss some of useful JavaScript's methods in LWC and Lightning Component , below are some of the functions

We will  use the below students example to understand these javascript methods.

const students = [
        {name: 'Brahmaji', id: 1, favsubject:'Science', rank: 1, percentage: 98},
        {name: 'Rohit', id: 2, favsubject:'Maths', rank: 3, percentage: 96},
        {name: 'Sachin', id: 3, favsubject:'History', rank: 2, percentage: 97},
        {name: 'Virat', id: 4, favsubject:'Social', rank: 4, percentage: 95},
        {name: 'Raj', id: 5, favsubject:'English', rank: 6, percentage: 79},
        {name: 'Vijay', id: 6, favsubject:'Science', rank: 5, percentage: 89},
];

forEach()

forEach() works similar to traditional for-loop but in simpler way. It basically iterates each element in the array with the provided function.

//foreach - ES6 way of iterating each element of array 
let studentsForEach = students.forEach(function(eachstudent){
	console.log(eachstudent.name);
});
> "Brahmaji"
> "Rohit"
> "Sachin"
> "Virat"
> "Raj"
> "Vijay"

map()

map() method creates a new array populated with the results of calling function on every element in an array. The best part of this method is it does not alter the original array.

//map method returns new array populated with results of calling a provided function
//with functional expression
let studentNamesUsingFunction = students.map(function(eachstudent){
	return eachstudent.name;
});
> Array ["Brahmaji", "Rohit", "Sachin", "Virat", "Raj", "Vijay"]

arrow syntax =>

In short, => expression simplifies the callback function notation. Lets take an example to understand it in detail.

//map method example with fat arrow notation : It simplifies the notation - less verbose
//example 1
let studentNames = students.map(eachstudent => {
	return eachstudent.name;
});
console.log(studentNames);
//example 2: if there is only one statement to execute then skip {} too.
let studentpercentages = students.map(eachstudent => eachstudent.percentage);
console.log(studentpercentages);

both the examples give the same response. but only difference is the syntax. lets see below snippet to understand simplier way

the regular callback function is as below. 

function(eachstudent){
	return eachstudent.name;
}

and this can be written now as 

eachstudent => {
	return eachstudent.name;
}

or

eachstudent => eachstudent.name;

//if you do not have any parameters, we can even simplify it to

() => //do something

filter()

filter() method creates a new array with all elements that pass the filter condition implemented by the provided function.

For example, if we want filter all students whose percentage more than 90.

//filter - to filter records 
        let topStudents = students.filter(eachstudent => eachstudent.percentage > 90);
        console.log(topStudents);
> Array [Object { name: "Brahmaji", id: 1, favsubject: "Science", rank: 1, percentage: 98 }, 
Object { name: "Rohit", id: 2, favsubject: "Maths", rank: 3, percentage: 96 }, 
Object { name: "Sachin", id: 3, favsubject: "History", rank: 2, percentage: 97 }, 
Object { name: "Virat", id: 4, favsubject: "Social", rank: 4, percentage: 95 }]

find()

find() method returns the value of the first element in the provided array that satisfies the provided testing function.

//find example - returns the value of the first element that satisfies the condition.
let sachinrecord = students.find(eachstudent => eachstudent.name = 'sachin');
console.log(sachinrecord);
> Object { name: "sachin", id: 1, favsubject: "Science", rank: 1, percentage: 98 }

Object.assign(….)

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

This method is going to be used in multiple places for example: in flattening objects while using lightning-datatable & etc.

//Object.assign - method copies all enumerable own properties from one or more source objects to a target object
//add new property including existing properties - merge
let newsachinrecord = Object.assign({fullName: 'Sachin tendulkar'}, sachinrecord);
console.log(newsachinrecord);
> Object { fullName: "Sachin tendulkar", name: "sachin", id: 1, favsubject: "Science", rank: 1, percentage: 98 }

slice()

slice() method returns shallow copy of an array into a new array. This can be a just copying selected elements or clone of an array. The best part of it is it does not modify original array.

//To generate a duplicate array - example 1
let studentsdup = students.slice();
console.log(studentsdup);
//To generate an array with first two elements - example 2
let studentsdup = students.slice(0, 2);
console.log(studentsdup);
> [
{ name: "Brahmaji", id: 1, favsubject: "Science", rank: 1, percentage: 98 }, 
{ name: "Rohit", id: 2, favsubject: "Maths", rank: 3, percentage: 96 }
]

reduce()

as name suggests, it reduces the array to single output.

let studentpercentages = students.map(eachstudent => eachstudent.percentage);
console.log(studentpercentages);
//reduce - as name suggests it reduces the array to single output
let averagepercentage = studentpercentages.reduce((eachstudent, nextstudent) => eachstudent + nextstudent);
console.log(averagepercentage/studentpercentages.length);
> Array [98, 96, 97, 95, 79, 89]
> 92.33333333333333

sort()

sort() method sorts the elements of an array in place and returns the sorted array. Default sorting order is ascending.

This example sorts students based on percentage.

//sort example - sort with percentage
let sortbypercentage = students.sort((a, b) => 
	{ return (a.percentage > b.percentage ? -1 : 1); });
console.log(sortbypercentage);

JSON.stringfy()

there will be many situations where we need to convert object to JSON string.

//find example - returns the value of the first element that satisfies the condition.
let sachinrecord = students.find(eachstudent => eachstudent.name = 'sachin');
console.log(sachinrecord);

//Convert object to string
let sachinStr = JSON.stringify(sachinrecord);
console.log(typeof sachinStr);

Output:
> Object { name: "sachin", id: 1, favsubject: "Science", rank: 1, percentage: 98 }
> "string"

JSON.parse()

to convert json string to javascript object, as per the json string.

//convert string to object
let sachinObj = JSON.parse(sachinStr);
console.log(sachinObj);