[SalesForce] LWC not showing Apex return value

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.

Best Answer

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;
            });
    }
}
Related Topic