Saturday 30 January 2021

 @wire with dynamic parameters

Call to apex method using @wire is executed at the time component loads. But suppose we want to make server call when a particular parameter changes.

So for that we can @wire an apex method with a dynamic parameter. We need to pass a parameter with “$” appended to it while making call to apex method. So, once the value of this property changes, call to apex is made at that time.

Apex class

public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContactList(){
    List<Contact> contactList = [SELECT id,lastName from contact LIMIT 10];
    return contactList;
}
}

html

<template>
<lightning-card title="wire with dynamic paramters" icon-name="custom:custom19">
<!-- Show contact if end-->
<lightning-input type="checkbox" label="Show Contacts Details" checked={showContacts} onchange={handleFlag}>
</lightning-input>

<!-- Show contact if check-->
<template if:true = {showContacts} icon-name="standard:contact">
<template for:each={conList} for:item="contact">
        <p key = {contact.LastName} >
            contact name : {contact.LastName}
        </p>
    </template>
</template>
</lightning-card>
</template>

js

import { LightningElement,wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList'
export default class DynamicProperty extends LightningElement {
    conList ;
showContacts = false;

handleFlag(event){
    this.showContacts = event.target.checked;

}
@wire (getContactList,{flag : '$showContacts'})
contactList({error,data}){
    if(error){
        console.log('error is-->'+error);

    }
    else if(data){
        this.conList = data;
    }

}

xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

1 comment: