# When should an architect choose Imperative Apex over the @wire service for server-side communication?

**Topic:** LWC · **Difficulty:** Medium · **Tags:** LWC, Imperative Apex, Server Communication

Read it on the site: https://www.forcechallenges.com/interview-questions/when-should-an-architect-choose-imperative-apex-over-the-wire-service-for-server-side-communication

## Answer

**Basics:** Both approaches call an `@AuraEnabled` Apex method. `@wire` is declarative and automatic. Imperative Apex is a plain function call that returns a Promise, so you control when it runs and what happens with the result.

**How it works:**
1. Import the method: `import saveLead from '@salesforce/apex/LeadController.saveLead';`.
2. Call it from an event handler, `connectedCallback`, or anywhere: `saveLead({ lead: this.draft }).then(...).catch(...)`, or use `async/await` in `try/catch`.
3. Pass parameters as an object whose keys match Apex parameter names.
4. On failure, the rejection contains `error.body.message` (and `error.body.fieldErrors` or `pageErrors` for DML errors surfaced via `AuraHandledException`).
5. After a write, refresh any wired data with `refreshApex`, or notify LDS with `getRecordNotifyChange`.

**Advanced / deep dive:** Wire requires `cacheable=true`, which forbids DML. Imperative can call both cacheable and non-cacheable methods. Reasons to prefer imperative: DML, calls with parameters not known until a click, sequencing several calls, calling in loops with different arguments, wanting fresh data every time, and needing finer error and spinner control. Reasons to prefer wire: automatic refresh on parameter change, shared client cache, less code, and integration with LDS. Architect-level considerations: batching multiple server calls into one Apex method reduces round trips; throw `AuraHandledException` with a safe message because other exception text is replaced by a generic error; enforce `with sharing` and `WITH USER_MODE` or `stripInaccessible` because Apex does not enforce FLS by default; mind the transaction governor limits per call; for long operations use a Queueable plus a platform event or polling rather than holding the UI.

**Code / config example:**
```javascript
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import createCase from '@salesforce/apex/CaseController.createCase';

export default class CaseCreator extends LightningElement {
    isSaving = false;
    async handleSave() {
        this.isSaving = true;
        try {
            const id = await createCase({ subject: this.subject });
            this.dispatchEvent(new ShowToastEvent({ title: 'Created', message: id, variant: 'success' }));
        } catch (e) {
            this.dispatchEvent(new ShowToastEvent({ title: 'Error', message: e.body?.message, variant: 'error' }));
        } finally { this.isSaving = false; }
    }
}
```
```apex
public with sharing class CaseController {
    @AuraEnabled   // not cacheable: DML allowed
    public static Id createCase(String subject) {
        try { Case c = new Case(Subject = subject); insert as user c; return c.Id; }
        catch (Exception e) { throw new AuraHandledException(e.getMessage()); }
    }
}
```

**Hidden gotchas & must-remember points:**
- `cacheable=true` methods cannot do DML; the call fails at runtime.
- Imperative results are not auto-refreshed; `refreshApex` only works on wired results.
- Only `AuraHandledException` messages reach the client reliably; other exceptions give a generic message.
- Apex does not enforce FLS or CRUD by default; add `WITH USER_MODE` or `Security.stripInaccessible`.
- Users need Apex class access through profile or permission set.
- Parameter names are case-sensitive keys in the JS object.

**Best practice:** Wire for reads, imperative for writes and event-driven calls, always with explicit error handling.

---
Source: ForceChallenges · last updated 2026-11-02
