Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

Wire Apex method to a function using @wire decorator in LWC

Let's look at how to Wire the Apex method to a function using @wire decorator in LWC.

By Teja, ex-Salesforce engineer · Updated March 17, 2021 · 1 min read

This is the best option when it comes to using @wire decorator, tell you why with this variant we can debug the data that we get back from the Apex method.

It's not that we cannot debug it when we wire an Apex method with a property, but there is a bit of process that's involved to see the output with this approach. We need to use the template file and use <template for:each="" for:item=""></template> to debug the code.

Let me walk you through the sample code.

public with sharing class DatatableController {
    public DatatableController() {

    }
    //it's mandate to use cacheable=true
    @AuraEnabled(cacheable=true)
    public static List<Account> allRecords(){
        return [SELECT Id, Name, Rating FROM Account];
    }
}

DatatableController.cls

And here is the controller file!

import { LightningElement, wire } from "lwc";

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

export default class DataTable extends LightningElement {
  @wire(allRecord)
  records({ error, data }) {
    if (data) {
      console.log(data);
    } else {
      console.log(error);
    }
  }
}

datatable.js

Hope this helps!

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts