How to display the data with imperative method in LWC
=========
Apex Class
==========
public class AccountController
{
@AuraEnabled
public static List<Account> displayAccounts(){
List<Account> acclist=[select Id,Name from Account LIMIT 5];
return acclist;
}
}
displayAccounts.html
====================
<template>
<lightning-button label="Load Accounts" variant="brand" onclick={handleClick}>
</lightning-button>
<template if:true={records}>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td><b>Name</b></td>
</tr>
<template for:each={records} for:item="acc">
<tr key={acc.Id}>
<td>{acc.Name}</td>
</tr>
</template>
</table>
</template>
<template if:true={error}>
Error in fetching the data
</template>
</template>
displayAccounts.js
==================
import { LightningElement,api } from 'lwc';
import displayAccounts from '@salesforce/apex/AccountController.displayAccounts';
export default class DisplayAccounts extends LightningElement {
@api records;
@api error;
handleClick(){
displayAccounts()
.then(result=>{
this.records=result;
this.error=undefined;
})
.catch(error=>{
this.error=error;
this.records=undefined;
});
}
}
LightningApplication
====================
<aura:application extends="force:slds">
<c:displayAccounts/>
</aura:application>
Comments
Post a Comment