I have created a simple LWC to display a list of account records in a box on clicking of a button but the records displayed on the grid are getting repeated.
Controller:
public with sharing class AccountController {
@AuraEnabled
public static List<AccountDetailsWrapper> getAccountDetails(){
try {
List<AccountDetailsWrapper> wrapperList = new List<AccountDetailsWrapper>();
AccountDetailsWrapper wrapperObj = new AccountDetailsWrapper();
String baseUrl = URL.getSalesforceBaseUrl().toExternalForm() + '/';
for (Account acc : [SELECT Id, Name, Phone, Type, Website FROM Account]){
wrapperObj.accountId = baseUrl + acc.Id;
wrapperObj.accountName = acc.Name;
wrapperObj.accountPhone = acc.Phone;
wrapperObj.accountType = acc.Type;
wrapperObj.accountWebsite = acc.Website;
wrapperList.add(wrapperObj);
}
return wrapperList;
}
catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
public class AccountDetailsWrapper{
@AuraEnabled
public String accountId{get; set;}
@AuraEnabled
public String accountName{get; set;}
@AuraEnabled
public String accountPhone{get; set;}
@AuraEnabled
public String accountType{get; set;}
@AuraEnabled
public String accountWebsite{get; set;}
}
}
HTML:
<template>
<lightning-card title="Account Grid">
<lightning-button class="slds-p-around_medium" label="Show accounts in grid" onclick={showAccounts}
variant="brand"></lightning-button>
<lightning-layout class="slds-p-around_medium" multiple-rows>
<template if:true={hasData}>
<template for:each={accounts} for:item="account">
<lightning-layout-item class="slds-m-around_large" key={account.accountId} size="2">
<div class="slds-box slds-align_absolute-center">
<!-- <lightning-formatted-text value={account.Name}></lightning-formatted-text> -->
<lightning-formatted-url label={account.accountName} value={account.accountId}
target="_blank"></lightning-formatted-url>
</div>
</lightning-layout-item>
</template>
</template>
</lightning-layout>
</lightning-card>
JS:
import { LightningElement, track, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccountDetails';
export default class AccountGrid extends LightningElement {
@track accounts;
error;
hasData = false;
// @wire(getAccounts)
// getAllAccounts({data, error}){
// if(data){
// this.hasData = data.length > 0 ? true : false;
// this.accounts = data;
// console.log(JSON.stringify(this.accounts))
// this.error = undefined;
// }
// else{
// this.error = error;
// this.data = undefined;
// }
// }
showAccounts(){
getAccounts()
.then(result => {
this.accounts = result;
console.log(JSON.stringify(this.accounts));
this.hasData = result.length > 0 ? true : false;
}).catch(error => {
this.error = error.body.message;
})}
}
Output:

AccountDetailsWrapper wrapperObj = new AccountDetailsWrapper();inside the loop, not the outside.