0

I have a class in apex and a few methods inside. I want to declare a variable that can be used in all methods.

public class Address_Penetration_ApexController {  
    public List<String> neverUnits = new List<String>();
    @AuraEnabled
    public static list getAddress_Penetration(String civicAddress,String streetName,String streetType,String city,String province) {             
        neverUnits.add("apple");
    neverUnits.add("mango");
    }   
    public static list getAddress_NeverUnits() {
        return neverUnits;
    }    
}

These are the error messages I get when I run the above code

enter image description here

5

You cannot store state in your server-side Aura or LWC controllers. All state must be stored on the client in your components' variables and passed in to your server-side controllers.

Here, neverUnits is declared as an instance variable, so you cannot access it from a static method (which doesn't have an instance associated with it). That's why you're getting a syntax error instead of unexpected runtime behavior.

Even if you did declare it static, however, it would not persist values across calls to the server because that's not supported in Lightning controllers.

1

Add static to the list declaration. public static List<String> neverUnits = new List<String>();

This will associate the variable with the class. Static methods only have access to static variables. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_static.htm

https://csawesome.runestone.academy/runestone/books/published/csawesome/Unit5-Writing-Classes/topic-5-7-static-vars-methods.html

You also need to annotate the method getAddress_NeverUnits with @AuraEnabled like you did with the method getAddress_Penetration to give your component access to the method.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_AuraEnabled.htm

2
  • 1
    As said by David Reed the static variable will be reset on each invocation of an AuraEnabled method so this is not a solution.
    – Phil W
    Dec 19 '20 at 21:02
  • Thank you @David. Something that I was not aware of.
    – sumchans
    Dec 20 '20 at 17:36

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.