Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 36 ยท Lightning Web Components

Calling Apex from LWC with @wire and Imperative Calls

Learn how a Lightning Web Component calls Apex: @AuraEnabled(cacheable=true), @wire, imperative calls, error handling and refreshApex, with a runnable JavaScript stand-in.

An LWC runs in the browser, but your data and business rules live in Salesforce. To reach them, a component either uses the Lightning Data Service (standard record forms and wire adapters, no Apex needed) or calls an Apex method you wrote. This lesson shows both Apex styles: the reactive @wire approach for reading data and the imperative approach for actions and writes. It builds on events and reactivity and on the Apex classes you already know.

Real calls need an org, so the LWC and Apex listings are read-only. The runnable example is a JavaScript stand-in that models the promise-based shapes, with fake data, labelled as a stand-in.

Step 1: an Apex method the component may call

APEX
public with sharing class AccountController {

    @AuraEnabled(cacheable=true)
    public static List<Account> getTopAccounts(Integer maxRows) {
        return [SELECT Id, Name, Industry, AnnualRevenue
                FROM Account
                WHERE AnnualRevenue != null
                WITH USER_MODE
                ORDER BY AnnualRevenue DESC
                LIMIT :maxRows];
    }

    @AuraEnabled
    public static Account renameAccount(Id accountId, String newName) {
        Account a = new Account(Id = accountId, Name = newName);
        update as user a;
        return a;
    }
}

Requirements: the method is public or global, static, and annotated @AuraEnabled. The annotation name is historical (from Aura components); LWC uses it too. cacheable=true means the result may be cached on the client and the method must be read-only (no DML). Methods that change data omit cacheable.

Step 2a: @wire for reading data

Import the method and wire it to a property or function:

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

export default class TopAccounts extends LightningElement {
    maxRows = 5;

    @wire(getTopAccounts, { maxRows: '$maxRows' })
    accounts;
}

The '$maxRows' string with a leading $ makes the parameter reactive: when maxRows changes, the wire calls Apex again. The result is { data, error }:

HTML
<template>
  <template lwc:if={accounts.data}>
    <ul>
      <template for:each={accounts.data} for:item="a">
        <li key={a.Id}>{a.Name}: {a.AnnualRevenue}</li>
      </template>
    </ul>
  </template>
  <template lwc:elseif={accounts.error}>
    <p>Something went wrong.</p>
  </template>
</template>

Wire to a function when you need to process the result:

JavaScript
@wire(getTopAccounts, { maxRows: '$maxRows' })
wiredAccounts({ data, error }) {
    if (data) {
        this.rows = data.map(a => ({ ...a, label: `${a.Name} (${a.Industry})` }));
        this.error = undefined;
    } else if (error) {
        this.error = error;
        this.rows = undefined;
    }
}

The data returned is read-only; copy it with spread before changing it.

Step 2b: imperative calls

Call the method yourself, usually in a handler, for actions that change data or that must run only on a click:

JavaScript
import renameAccount from '@salesforce/apex/AccountController.renameAccount';

async handleSave() {
    try {
        const saved = await renameAccount({ accountId: this.recordId, newName: this.newName });
        this.status = `Saved ${saved.Name}`;
    } catch (error) {
        this.status = error.body ? error.body.message : error.message;
    }
}

Arguments are passed as one object whose keys match the Apex parameter names. The call returns a promise.

Refreshing wired data

After a DML action, the cached wire result is stale. Keep the wire's returned value in a field and call refreshApex:

JavaScript
import { refreshApex } from '@salesforce/apex';

@wire(getTopAccounts, { maxRows: '$maxRows' })
wiredResult;

async handleSave() {
    await renameAccount({ accountId: this.recordId, newName: this.newName });
    await refreshApex(this.wiredResult);
}

Errors

An exception thrown in Apex reaches the client as an object with body.message. To show a clean message, throw an AuraHandledException:

APEX
throw new AuraHandledException('Name cannot be blank');

Wire or imperative?

Use @wire when Use imperative when
Reading data to display A user action triggers it (click, save)
Parameters change reactively The method does DML (not cacheable)
Cached results are acceptable You need exact control over timing

Before writing Apex at all, check whether a base component (lightning-record-form, lightning-record-edit-form) or a wire adapter such as getRecord from lightning/uiRecordApi covers your need; they handle field-level security and caching for you.

Try the idea: reactive wire vs imperative (JavaScript stand-in)

JS Stand-in: a wire re-runs when its parameter changes (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second refresh() makes no call because the parameters did not change, which mirrors how wired, cacheable methods avoid repeat trips.

Try the idea: an imperative call with error handling (JavaScript stand-in)

JS Stand-in: try/catch around an async call (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which annotation must an Apex method have to be callable from an LWC?

    @AuraEnabled exposes a public static method to Lightning components, including LWC.
  2. 2. What does the $ in { maxRows: '$maxRows' } mean in a @wire config?

    A leading $ makes the wire track the component field named after it.
  3. 3. Which Apex methods may be marked cacheable=true?

    Cacheable methods must not change data, because results can be served from the client cache.
  4. 4. What do you call after an imperative save to refresh a wired list?

    refreshApex re-runs the wire and bypasses the cache for that result.

Summary

  • Expose Apex with @AuraEnabled; add cacheable=true for read-only methods used by @wire.
  • @wire is reactive and declarative; imperative calls are for actions and DML.
  • Wired data is read-only; use refreshApex after changes.
  • Prefer base components and Lightning Data Service when they cover the need.

Next: LWC Lifecycle Hooks and Jest Testing