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;
}