Intermediate 20 min read

Calling Apex with @wire vs. Imperatively

By the end of this lesson, you'll be able to:

  • Call an Apex method reactively using @wire
  • Call an Apex method imperatively using async/await
  • Choose the right approach for a given situation

Prerequisites: "@AuraEnabled and cacheable=true"

@wire with an Apex Method

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

export default class AccountList extends LightningElement {
    @wire(getAccounts)
    accounts;
}

This gets the same reactive, cached benefits as @wire(getRecord, ...) from Module 6 — but it requires the Apex method to be cacheable=true.

Calling Apex Imperatively

import getAccounts from '@salesforce/apex/AccountController.getAccounts';

async handleSearch() {
    try {
        this.accounts = await getAccounts({ searchTerm: this.searchTerm });
    } catch (error) {
        this.error = error;
    }
}

Imported the same way, but called directly as a function — it returns a Promise (Module 4's async/await applies directly). Use this for on-demand calls not tied to the component's lifecycle, and for any method that performs DML, since those can never be cacheable=true and therefore can't be used with @wire.

Choosing Between Them

Situation Use
Data should load automatically when the component renders @wire
Data should re-fetch automatically when an input changes @wire with a reactive parameter
The method performs DML (insert/update/delete) Imperative call — never @wire
The call should happen in response to a specific user action (e.g. a button click) Imperative call

Exercise

A method searchAccounts(searchTerm) is cacheable=true and should re-run automatically whenever the user's typed search term changes. Write the @wire declaration using a reactive parameter.

Show hint

Recall the $ prefix pattern from Module 6.

JAVASCRIPT

Exercise

Challenge: explain, as a comment, why a method that inserts a new record can never be called via @wire.

Show hint

Recall the cacheable=true requirement.

JAVASCRIPT

Calling Apex with @wire vs. Imperatively Quiz

1. What must an Apex method be to be usable with @wire?

2. What does an imperative Apex call return?

3. A method that performs DML can be called via @wire as long as it is marked cacheable=true.

4. When is an imperative call the right choice over @wire?

5. What LWC concept does calling Apex imperatively directly rely on?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Apex methods can be called the same two ways record data can — declaratively via @wire for automatic, reactive, cached reads, or imperatively for on-demand calls and any operation that writes data.