4

I initialize the list at the beginning of the code. In one of the methods, I add values ​​to it. In another method, the list is already empty. But I need these values ​​in the second method. How to save them to get after?

public static List<String> listsIds = new List<String>();

@AuraEnabled
public static List<Object> getLists(){
//If I initialize the list here, nothing will change: "listsIds" will be null

    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('myEndpointIsHere');
    request.setMethod('GET'); 
    HttpResponse response = http.send(request);

    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    List<Object> lists = (List<Object>) results.get('lists');
    List<String> listsNames = new List<String>();

    for(Object oneList : lists){
        String listInText = String.valueOf(oneList);
        String listName = listInText.substringBetween('name=', '}');
        String listId = listInText.substringBetween('id=', ',');
        listsNames.add(listName);
        //Here I added the values:
        listsIds.add(listId);
    }
    return listsNames;
}

@AuraEnabled
public static void testIt(){
    //Empty List:
    System.debug(listsIds);
}

1 Answer 1

7

static methods share state (in the form of static variables) only in the context of a single transaction. Each Lightning server call to an @AuraEnabled method takes place in a separate transaction; no state is stored on the server across such invocations. Each such method will start with the same value for listIds, which is an empty list - your initializer will be run anew on each invocation.

Your state needs to be stored on the client, in attributes of your Lightning component. Your client-side controller can then pass needed state to your Apex methods as a parameter. You will not be able to store it on the server in this way unless you choose to persist it as an object, which will add a lot of complexity and is likely something you'd want to do only if the data is large, long-lived, and expensive to compute.

2
  • 1
    Beat me to it :)
    – gNerb
    Commented Jun 24, 2019 at 16:51
  • Thank you :)))) Commented Jun 24, 2019 at 17:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .