Using an iterator in the template in Lightning Web Component

When we get data from objects using Apex we need to follow a series of steps to display them back to the users.

We need to check if the data is not null and then we need to loop them through an iterator to go over all the records one after other and for that, we would need a tag which is <template for:each={} for:item=""></template>

Let's look at some sample code!

This is a simple Apex Class that sends data by querying it.

public with sharing class ExploreIteratorController {
  public ExploreIteratorController() {
  }

  @AuraEnabled(cacheable=true)
  public static List<Account> getRecords() {
    try {
      return [SELECT Id, Name, Rating, Industry FROM Account];
    } catch (Exception e) {
      throw new AuraHandledException(e.getMessage());
    }
  }
}
ExploreIteratorController.cls

This here is the controller file in the Lightning Web Component since in which we are trying to pipe the output of the Apex method to a property.

import { LightningElement, wire } from "lwc";

import getRecords from "@salesforce/apex/ExploreIteratorController.getRecords";

export default class ExploreIterators extends LightningElement {
  @wire(getRecords)
  records;
}
exploreIterators.js

This is the template file and we are checking that the data is not null and then we are passing records.data to <template for:each={} for:item=""></template> tag.

We need to make sure every row should be associated with an attribute called key and the value that we provide to it should be unique. That's how Lightning gets to a record if it gets modified and updates it with the current value.

<template>
  <!-- check the data is not null -->
  <template if:true={records.data}>
    <!-- loop over through the data -->
    <template for:each={records.data} for:item="record">
      <!-- always provide unique value for key attribute -->
      <p key={record.Id}>
        {record.Id} 
        {record.Name} 
        {record.Industry} 
        {record.Rating}
      </p>
    </template>
  </template>
</template>

exploreIterators.js

Hope this is helpful!