Skip to main content
This component demonstrates how to call an Apex method imperatively while passing parameters. This pattern is ideal for search functionality and user-driven operations.

Implementation

import { LightningElement } from 'lwc';
import findContacts from '@salesforce/apex/ContactController.findContacts';

export default class ApexImperativeMethodWithParams extends LightningElement {
    searchKey = '';
    contacts;
    error;

    handleKeyChange(event) {
        this.searchKey = event.target.value;
    }

    async handleSearch() {
        try {
            this.contacts = await findContacts({ searchKey: this.searchKey });
            this.error = undefined;
        } catch (error) {
            this.error = error;
            this.contacts = undefined;
        }
    }
}

Key Features

Passing Parameters

Pass parameters as an object with property names matching Apex parameter names:
this.contacts = await findContacts({ searchKey: this.searchKey });
//                                  ^
//                                  Parameter object

Parameter Object Syntax

await findContacts({ searchKey: this.searchKey })
//                   ^          ^
//                   |          |
//                   |          Component property value
//                   Apex parameter name

Separate Input Handling

Handle input changes separately from search execution:
handleKeyChange(event) {
    this.searchKey = event.target.value; // Update property
}

async handleSearch() {
    // Execute search when user clicks button
    this.contacts = await findContacts({ searchKey: this.searchKey });
}

User-Controlled Execution

The search only executes when the user clicks the Search button:
<lightning-button
    label="Search"
    onclick={handleSearch}
></lightning-button>

Properties

PropertyTypeDescription
searchKeyStringThe current search input value
contactsArrayList of contacts matching the search
errorObjectError object if the call fails

Parameters

Apex Method Parameters

ParameterTypeDescription
searchKeyStringSearch term to filter contacts by name

Error Handling

Use try/catch to handle errors gracefully:
try {
    this.contacts = await findContacts({ searchKey: this.searchKey });
    this.error = undefined;
} catch (error) {
    this.error = error;
    this.contacts = undefined;
}

Multiple Parameters Example

For methods with multiple parameters:
// Apex method signature:
// public static List<Contact> findContacts(String searchKey, Integer limitSize, String orderBy)

// JavaScript call:
this.contacts = await findContacts({
    searchKey: this.searchKey,
    limitSize: 20,
    orderBy: 'Name'
});

Parameter Types

Supported parameter types:
JavaScript TypeApex Type
StringString
NumberInteger, Decimal, Double
BooleanBoolean
ObjectCustom Apex class, sObject
ArrayList
null/undefinednull

When to Use

Use imperative calls with parameters when:
  • Search functionality needs a submit button
  • You want to validate input before calling Apex
  • You need to combine multiple inputs into one call
  • You want to avoid calling Apex on every keystroke
  • You need to perform operations before/after the Apex call

Comparison with Wire and Parameters

FeatureImperativeWire with Params
ExecutionOn button clickAutomatic on param change
ControlFull controlAutomatic
DebouncingNot neededRequired
ValidationBefore callNot possible
User actionExplicit (button)Implicit (typing)

Best Practices

  1. Validate input: Check parameters before calling Apex
  2. Handle empty input: Decide behavior for empty search
  3. Clear previous results: Reset state on new search
  4. Show feedback: Indicate search in progress
  5. Handle no results: Show appropriate message

Advanced Example with Validation

async handleSearch() {
    // Validate input
    if (!this.searchKey || this.searchKey.length < 2) {
        this.error = { message: 'Please enter at least 2 characters' };
        return;
    }

    this.isLoading = true;
    try {
        this.contacts = await findContacts({ searchKey: this.searchKey });
        this.error = undefined;
        
        // Handle empty results
        if (this.contacts.length === 0) {
            this.error = { message: 'No contacts found' };
        }
    } catch (error) {
        this.error = error;
        this.contacts = undefined;
    } finally {
        this.isLoading = false;
    }
}

UI Layout

The component uses Lightning Layout for a clean search interface:
<lightning-layout vertical-align="end">
    <lightning-layout-item flexibility="grow">
        <!-- Search input takes available space -->
    </lightning-layout-item>
    <lightning-layout-item class="slds-var-p-left_xx-small">
        <!-- Button aligned to the right -->
    </lightning-layout-item>
</lightning-layout>

Build docs developers (and LLMs) love