1

I am new to LWC. I created an Apex method and want to show the returned string value in the HTML file when the button is clicked but for some reason it is not working.

Apex class:

public with sharing class MyController {
    
   @AuraEnabled(Cacheable = true)
    public static String testApexMethod(){
       return 'This string is returned from Apex method';
    } 
}

HTML:

<template>
  <lightning-button label="Test" onclick={apexMethod}></lightning-button>
</template>

JS File:

import { LightningElement, api, wire, track } from 'lwc';
import testApexMethod from '@salesforce/apex/MyController.testApexMethod';
export default class WireDemo extends LightningElement {
showLabel;
 @wire(testApexMethod)
    apexMethod(event) { this.showLabel = event.data; }
}

When I refresh the page, it displays the returned string. But I want the method to be executed only when the button is clicked.

2

Here you are doing a @wire call to the apex which will be called as soon as your component is rendered.

In such a requirement where you want to call apex on a click, you should use an imperative call to apex.

Your JS should look something like this.

import { LightningElement, api, wire, track } from 'lwc';
import testApexMethod from '@salesforce/apex/MyController.testApexMethod';
export default class WireDemo extends LightningElement {
    showLabel;

    apexMethod() {
        testApexMethod()
            .then(result => {
                this.showLabel = result;
            })
            .catch(error => {
                this.showLabel = error;
            });
    }
}
1
  • it works. thanks
    – Hari Ha
    May 12 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.