Invoke Apex method using @wire decorator in LWC

This is the first and simple variant when it comes to invoking an Apex method from LWC, which is by using @wire decorator.

This is the first and simple variant when it comes to invoking an Apex method from LWC.

The name itself conveys everything, we will be wiring the output of the apex method to a property.

If the apex method returns back a Map, then it will be received as an object by the property, if the apex method sends back a List it will be received as an Array in the Web Component.

Let’s look at how to draft the code in such a way the data is sent back by apex method and wired to the property.

public with sharing class DatatableController {
    // it's a mandate to have the method cacheable as true
    @AuraEnabled(cacheable=true)
    public static List<Account> allRecords(){
        return [SELECT Id, Name, Rating FROM Account];
    }
}
DatatableController.cls

Here is the JavaScript file of the Web Component.

import { LightningElement, wire } from 'lwc';

import allRecord from '@salesforce/apex/DatatableController.allRecords';

export default class DataTable extends LightningElement {

        //wiring the output of the method to a property
    @wire(allRecord)
    records;
}
dataTable.js

In the template file we are iterating through the list. Note that we will be using {records.data} and not record in <template for:each for:item> tag.

<template>
  <template if:true={records}>
    <template for:each={records.data} for:item="record">
      <p key={record.Id}>{record.Name}</p>
    </template>
  </template>
</template>

dataTable.html

Hope this is helpful!