function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Andrew EAndrew E 

Initialize controller constructor in Lightning

Hello,

I have a Lightning Component with an Apex controller. The controller has a constructor that sets some variables, but it doesn't seem to be running when I load my component because the variable is null when I call another function. I can't call it from the component either as I get a notification that "AuraEnabled does not apply to Constructors".
 

See below for an example of what I mean but my case is a lot more complex as I have quite a few variables that need to be set at the beginning and calling a SOQL query every time I call a function that needs these would not be efficient. 
 

public class MyController{

   public User currentUser;

   public MyController(){
      currentUser = [Select Id, FirstName from User where  Id =: UserInfo.getUserId();]
   }

    @AuraEnabled
   public static String getMyName(){
      return currentUser.FirstName;
   }

}
Prithviraj_ChavanPrithviraj_Chavan
Hi Andrew,
You just need to declare currentUser as static...
@AuraEnabled
    public Static User currentUser{get;set;}
    public CustomComponents(){
        currentUser = [Select Id, FirstName from User where  Id =: UserInfo.getUserId()];
        system.debug('currentUser	::	'+currentUser);
    }
    @AuraEnabled
    public static String getMyName(){
        return currentUser.FirstName;
    }
if you find my solution helpful then please make this as best answer...
 
Andrew EAndrew E
Thanks, I changed it to static and added {get; set;} as well but it's still not working.

I noticed you changed the name of my constructor from the class name. Am I supposed to name it after a component?