100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Integrating Apex with LWC

Learn how Lightning Web Components call Apex with @AuraEnabled methods, wire adapters, imperative calls, caching, and error handling patterns.

Practical ApexIntermediate10 min readJul 10, 2026
Analogies

Exposing Apex Methods to Lightning Web Components

A Lightning Web Component can only call Apex methods explicitly marked @AuraEnabled, and those methods must be public static (or, for cacheable reads, public static with cacheable=true). The cacheable=true flag tells the Lightning Data Service to cache the response client-side and enables the component to use the reactive @wire adapter instead of an imperative call — but it also means the method must be a pure read (no DML, no direct record modification) and its results are eligible for reuse across components without re-hitting the server. Import the method into a component's JavaScript file using the fully qualified path @salesforce/apex/Namespace.ClassName.methodName, where Namespace is omitted for unmanaged/unpackaged orgs.

🏏

Cricket analogy: cacheable=true is like a broadcaster reusing a previously captured replay clip for a boundary instead of re-filming the shot — once captured, the same footage (data) can be reused across multiple viewers without needing a fresh call to the camera crew.

Wire Adapter vs Imperative Apex Calls

The @wire adapter provisions data reactively — the component automatically re-invokes the Apex method whenever a reactive parameter (marked with the $ prefix, like $recordId) changes, and Lightning Data Service handles caching, cache invalidation on related DML, and error state — making it the right default for read operations that should stay in sync with the record. Imperative calls (await myApexMethod({ param }) inside a JS method, typically triggered by a button click or event handler) are necessary for anything with a side effect — inserts, updates, deletes — and for cases where you need explicit control over exactly when the call fires, such as debounced search-as-you-type or a multi-step form that only submits on a final button press.

🏏

Cricket analogy: The @wire adapter automatically re-fetching on parameter change is like a live scoreboard that updates itself the instant a run is scored, without anyone manually refreshing it — reactive by design, not on-demand.

javascript
import { LightningElement, api, wire } from 'lwc';
import getOpenOpportunities from '@salesforce/apex/OpportunityController.getOpenOpportunities';
import updateOpportunityStage from '@salesforce/apex/OpportunityController.updateOpportunityStage';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class OpenOpportunityList extends LightningElement {
    @api recordId; // Account Id, reactive via $recordId below
    opportunities;
    wiredResult;

    // Reactive read: re-runs automatically whenever recordId changes
    @wire(getOpenOpportunities, { accountId: '$recordId' })
    wiredOpps(result) {
        this.wiredResult = result; // keep reference for refreshApex()
        if (result.data) {
            this.opportunities = result.data;
        } else if (result.error) {
            this.showError(result.error);
        }
    }

    // Imperative call: has a side effect (DML), triggered by user action
    async handleStageChange(event) {
        const oppId = event.target.dataset.id;
        try {
            await updateOpportunityStage({ oppId, newStage: 'Closed Won' });
            await refreshApex(this.wiredResult); // re-sync the cached wire data
        } catch (error) {
            this.showError(error);
        }
    }

    showError(error) {
        this.dispatchEvent(new ShowToastEvent({
            title: 'Error updating opportunity',
            message: error.body ? error.body.message : error.message,
            variant: 'error'
        }));
    }
}

Refreshing Cached Data and Handling Errors

After an imperative DML call changes data that a @wire adapter previously cached, the component's displayed data goes stale unless you explicitly call refreshApex(wiredResultReference) — Salesforce cannot automatically know your imperative call invalidated a specific cache entry, so this must be done manually and requires holding onto the full result object (not just result.data) from the wire configuration. On the error side, an @AuraEnabled method should throw an AuraHandledException (not a raw exception) for any error you want the client to see with a useful message, because unhandled exceptions are deliberately obscured by Salesforce for security reasons and surface to the client as a generic error.

🏏

Cricket analogy: Needing refreshApex() after an imperative update is like a stadium's manual scoreboard operator who has to physically re-enter the score after a boundary is signaled — the system doesn't magically know a run was scored unless someone tells it.

Always keep the full wire result object (e.g., this.wiredResult = result) in a component property, not just result.data. refreshApex() needs that full reference, including its internal cache key, to correctly invalidate and re-fetch — passing it a plain data array will not work.

Passing Data Between Apex and LWC Correctly

Apex method parameters and return types map to JavaScript types through JSON serialization: Apex Id and String become JS strings, Integer/Decimal/Double become JS numbers, Boolean maps directly, and a List<sObject> becomes a JS array of plain objects with the sObject's field API names as keys. A common pitfall is passing a JavaScript Date object directly as a parameter expecting an Apex Date or Datetime — it must be serialized to an ISO string first. For complex parameters, define an Apex inner class (or a wrapper class) with public fields matching the JSON shape you want, since @AuraEnabled methods can accept and return custom Apex types as long as their fields are also @AuraEnabled or public.

🏏

Cricket analogy: Apex-to-JS type mapping is like translating a scorecard from a paper ledger format into a digital app's data format — the numbers and names have to map cleanly (runs stay numbers, player names stay strings) or the translation breaks.

Do not throw a raw custom exception (e.g., throw new MyCustomException('bad input');) from an @AuraEnabled method and expect the client to see that message. Salesforce strips detailed error information from uncaught exceptions before sending them to the client as a security precaution. Always catch the error and re-throw as new AuraHandledException(e.getMessage()), and remember AuraHandledException itself has a quirk where you must call .setMessage() if you construct it with new AuraHandledException() before throwing, since its default constructor message isn't automatically applied the way you'd expect.

  • Only public static methods marked @AuraEnabled can be called from a Lightning Web Component.
  • cacheable=true enables the reactive @wire adapter and client-side caching, but restricts the method to read-only operations.
  • Use @wire for reactive reads that should sync with reactive parameters; use imperative calls for anything with a DML side effect.
  • After an imperative DML call, invalidate stale @wire data explicitly with refreshApex(), holding the full wire result reference.
  • Apex types map to JS via JSON serialization; Dates must be passed as ISO strings and complex data needs a wrapper class.
  • Uncaught Apex exceptions are stripped of detail before reaching the client — always throw AuraHandledException with an explicit message.
  • Component-level field visibility is not a security control; CRUD/FLS/sharing must be enforced inside the Apex method itself.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#ApexSalesforceStudyNotes#IntegratingApexWithLWC#Integrating#Apex#LWC#Exposing#StudyNotes#SkillVeris#ExamPrep

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse