[SalesForce] How to use an apex class variable in LWC javascript

I have a constants class that has:

public static final String DATA_TYPE_INTEGER = 'INTEGER';

I tried to access this in my LWC by doing an import like this:

import DATA_TYPE_INTEGER from '@salesforce/apex/ConstantsClass.DATA_TYPE_INTEGER';

But in my Javascript, .toLowerCase() is not an operation on DATA_TYPE_INTEGER and I can't seem to get any actual string value from it.

I then tried in my apex class for my LWC:

@AuraEnabled
public final String DATA_TYPE_INTEGER = ConstantsClass.DATA_TYPE_INTEGER;

And importing that, but got the same issues. I don't think Lightning Components allowed you to access variables like this at all, but was thinking that LWCs might, like they can import custom labels…

Is this actually possible? And if so, how do I go about importing an apex class variable into my javascript?

Best Answer

There's no way at least of today to import constant values directly in JS from Apex. The only available way is to import Apex methods. You can actually utilize this for your use case here.

What you can do is to declare an apex method which returns your constant class ConstantsClass, and utilize it on your JS. This will in fact help you to get all the constant values in a single call. Sample below.

ConstantClass.cls

@AuraEnabled
public final String DATA_TYPE_INTEGER = 'INTEGER';

MyApexController.cls

@AuraEnabled(cacheable=true)
public static ConstantClass getAllConstants() {
    return new ConstantClass();
}

JS Controller

import getConstants from '@salesforce/apex/MyApexController.getAllConstants';

...

@wire(getConstants) 
allConstants ({error, data}) {
    if (data) {
        console.log(data.DATA_TYPE_INTEGER ); // will give you the value of your constant
    } else {
        this.error = error;
    }
} 
Related Topic