Sub topic 2
Importing the Apex Method into Your Component
This chapter covers the import statement that connects a Lightning Web Component (LWC) to an Apex method. It explains what the import gives you, how the path is built, and the errors you will meet when it is wrong.
It assumes you know basic JavaScript (ES modules, destructuring), the structure of an LWC (template, class, @api), and basic Apex and SOQL. You also need an org or scratch org where you can deploy code.
What the import does
An LWC cannot call Apex by name. It needs a reference to the method, and the reference comes from a scoped module import:
import getContacts from '@salesforce/apex/ContactController.getContacts';The import binds the name getContacts to a function. That function is not your Apex code. It is a client-side proxy that the platform generates when it compiles the component. When you call it, or when a wire adapter calls it for you, the proxy sends a request to the server, runs the Apex method, and returns the result.
The same imported function serves two purposes:
- You can pass it to
@wireas the first argument. The wire service then calls it for you. The next chapter covers this. - You can call it directly, like
getContacts({ accountId: '001...' }). It returns a promise. This is an imperative call, covered later in the tutorial.
Because one import supports both styles, you do not need a separate import for each.
Anatomy of the import path
The path has a fixed shape:
@salesforce/apex/[namespace.]ClassName.methodName| Part | Meaning | Example |
|---|---|---|
| `@salesforce/apex` | The scoped module for Apex methods | `@salesforce/apex` |
| `namespace` | Namespace of a managed package. Leave it out for code in your own org without a namespace. | `acme` |
| `ClassName` | The Apex class that holds the method | `ContactController` |
| `methodName` | The static method to expose | `getContacts` |
Separators matter. A slash follows apex, and dots separate the namespace, class, and method. For a class in a managed package with the namespace acme, the import looks like this:
import getContacts from 'acme/ContactController.getContacts';Do not copy that form. It is shown only to contrast with the correct one for a namespaced class:
import getContacts from '@salesforce/apex/acme.ContactController.getContacts';The local name on the left (getContacts) is yours to choose. It does not have to match the Apex method name. This is useful when two classes expose methods with the same name:
import getAccountContacts from '@salesforce/apex/ContactController.getContacts';
import getCaseContacts from '@salesforce/apex/CaseController.getContacts';The default import is the only form available. You cannot use named imports such as import { getContacts } from ... for Apex methods.
The Apex method behind the import
The import only works if the Apex method meets a few conditions. Here is the method used throughout this tutorial:
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}The requirements, each of which the import depends on:
- The method is
static. - The method is
publicorglobal, and so is its class. - The method has the
@AuraEnabledannotation. - For use with
@wire, the annotation includescacheable=true.
A method without cacheable=true can still be imported and called imperatively. It cannot be wired. Wire adapters require cacheable methods because they may call the method more than once and reuse results.
A method with cacheable=true has one more restriction: it must not perform DML (insert, update, delete) or other changes to data. The platform enforces this at runtime. If you need a method that changes data, leave out cacheable=true and call it imperatively.
Using the imported function in a component
Here is the import in a complete component. Only the import line matters in this chapter. The wiring is explained in the next one.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
}Notice the order of the import statements. lwc supplies the decorators and the base class. The Apex import is a separate statement. Import statements run once when the module loads, so the proxy exists before any instance of the component is created.
The key point is that getContacts in the @wire line is the imported function itself. You pass the function, not a string and not a call. Writing @wire(getContacts(), ...) or @wire('getContacts', ...) is a mistake.
How the platform resolves the import
The path is resolved when you deploy the component, not when a user opens the page. This is why many mistakes show up as deployment errors instead of runtime errors. The platform checks that the class and method exist and that the method is @AuraEnabled.
Two consequences follow:
- Renaming an Apex method breaks every component that imports it by the old name. The deploy fails, which is better than a silent runtime failure.
- Deploy the Apex class before, or together with, the component that imports it. If you deploy only the component and the class is missing in the target org, the deployment fails.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Deployment error saying the Apex method or class cannot be found | Typo in the path, wrong case, or the class is not deployed yet | Check each part of the path against the class. Deploy the class first. |
| Deployment error about the method being invalid for import | The method is not `static`, or not `public` or `global`, or lacks `@AuraEnabled` | Fix the method signature and annotation. |
| Runtime error when wiring: the method is not cacheable | `cacheable=true` is missing | Add `cacheable=true`, or call the method imperatively instead. |
| Runtime error from a cacheable method that writes data | The method performs DML | Remove the DML, or make the method non-cacheable and call it imperatively. |
| The import line is flagged by the editor but the code deploys | The editor has no type information for the org | Ignore it, or refresh the SFDX project's Apex metadata. |
| Component works for admins but not for other users | The user's profile cannot read the Apex class | Grant access to the class through a profile or permission set. |
The last row is easy to miss. Users need Apex class access to call the method, even when the code is correct. Class access is granted through a profile or a permission set. See the security chapter for how sharing and field-level security work inside the method.
Passing parameters
The imported function takes one argument: an object whose keys are the Apex parameter names.
getContacts({ accountId: '001000000000001AAA' });The key accountId must match the Apex parameter name accountId exactly. Position does not matter, because the arguments are matched by name. If a key is misspelled, the Apex parameter receives null, and the call does not fail on its own. With the method above, this returns no rows, which is hard to spot.
If the Apex method takes no parameters, call it with no argument, or leave out the second argument in @wire.
Imports and Jest
The import path is also what you mock in unit tests. Jest cannot resolve @salesforce/apex/... on its own, so the Salesforce Jest tooling provides a default resolver that turns each Apex import into a mock function. You replace it with your own using jest.mock and the same path string. The testing chapter covers this in detail. For now, note that the path you write in the component must be the path you mock.
Summary of rules
- Use the default import from
@salesforce/apex/[namespace.]Class.method. - The method must be
static, accessible, and annotated with@AuraEnabled. - Add
cacheable=trueto use the method with@wire. - Pass the imported function itself to
@wire, without calling it. - Match Apex parameter names exactly in the parameter object.
- Grant users access to the Apex class.
Exercise
A teammate writes import { getContacts } from '@salesforce/apex/ContactController.getContacts'; and the component fails. What is wrong, and how do you fix it?
Show answer
Apex methods are exposed as a default export, so named import syntax with braces does not work. Remove the braces: import getContacts from '@salesforce/apex/ContactController.getContacts';.
Exercise
The Apex method getContacts is public static with @AuraEnabled but no cacheable=true. The component uses @wire(getContacts, { accountId: '$recordId' }). What happens, and what are your two options?
Show answer
The wire fails because wire adapters require cacheable methods. Option one: add cacheable=true, which is valid only if the method does not perform DML. Option two: remove the wire and call the imported function imperatively, for example from an event handler.
Exercise
You import a method from a class in a managed package with the namespace acme. Write the import path for ContactController.getContacts.
Show answer
import getContacts from '@salesforce/apex/acme.ContactController.getContacts';