Lightning Web Component (LWC) to display a list of accounts

HTML (accountList.html):

<template>
    <lightning-card title="List of Accounts">
        <div class="slds-m-around_medium">
            <template if:true={accounts}>
                <template for:each={accounts} for:item="account">
                    <p key={account.Id}>{account.Name}</p>
                </template>
            </template>
            <template if:false={accounts}>
                <p>No accounts found</p>
            </template>
        </div>
    </lightning-card>
</template>

JavaScript (accountList.js):

import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';

export default class AccountList extends LightningElement {
    accounts;

    @wire(getAccounts)
    wiredAccounts({ error, data }) {
        if (data) {
            this.accounts = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.accounts = undefined;
        }
    }
}

Apex Controller (AccountController.cls):

public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccounts() {
        return [SELECT Id, Name FROM Account LIMIT 10];
    }
}

This Lightning web component retrieves a list of accounts from the server-side Apex controller method getAccounts using a wire adapter and displays them in a lightning-card component.

Leave a Reply

Back To Top