[SalesForce] LWC not calling Apex

I have a very simple LWC component with 2 input fields and a button that calls an Apex method. Unfortunately, I'm not able to reach to Apex class.

LWC Component:

<template>
    <lightning-input type="text" label="First Name" value={inputFirstName} onchange={updateFirstName}></lightning-input>
    <br/>
    <lightning-input type="text" label="Last Name" name="input3" value={inputLastName} onchange={updateLastName}></lightning-input>
    <br/>
    <lightning-button label="Login" onclick={handleAddRecord}></lightning-button>
</template>

LWC JS:

import { LightningElement, track, api, wire } from 'lwc';
import tryAddRecord from '@salesforce/apex/MyClass.addRecord';

export default class myTestLwc extends LightningElement {
    @api inputFirstName;
    @api inputLastName;

    handleAddRecord() {
        console.log(this.inputFirstName + ' ' + this.inputLastName);
        tryAddRecord({ 
            firstName : this.inputFirstName, 
            lastName : this.inputLastName
        })
        .then(result => {
            console.log('It is a success');
        })
        .catch(error => {
            console.log('You got an error');
        });
    }

    updateFirstName(event) {
        this.inputFirstName = event.detail.value;
    }

    updateLastName(event) {
        this.inputLastName = event.detail.value;
    }
}

Apex Class:

public class MyClass {
    @AuraEnabled
    public static String addRecord(String firstName, String lastName) {
        try{
            System.debug(firstName + ' ' + lastName);
            return 'testString';
        }
        catch (Exception ex) {
            return ex.getMessage();            
        }
    }
}

On button click, I have the correct values but I get console log "error" and I'm never hitting Apex method. What am I missing here?

Best Answer

You have API enabled input variables - which means they are not modifiable from the app.

For now, just take away the @api annotations on your two classes and this will likely fix the issue.

inputFirstName;
inputLastName;

If you do want to both set via an attribute, you could make a setter/getter:

@api
set inputFirstName(value) {
  this._inputFirstName = value;
}
get inputFirstName() {
  return this._inputFirstName;
}
_inputFirstName = "";

If this is not the cause of the problem - first, examine the error - normally they tell you something useful, then check your profile settings for your class to make sure you are able to access it from LWC

Related Topic