2

I have a very simple sample lightning component to understand the concept. I have button and on click on the button, I am incrementing a static variable in Apex Server controller. I am expecting that every time I click the button , the counter should increase and should display the incremented value on the Lightning Component UI. Counter variable is static variable in Apex code and is initialized to 0. But I am seeing opposite result, where counter increments from 0 to 1 for the first click of the button. But for subsequent clicks it doesn't increment.

Can anybody explain why this is happening ?

Below is my sample code -

Component -

<aura:component controller="LightningSampleServerController">

    <aura:attribute type="Integer" name="currentCount" />
    <ui:button label="Click Me" press="{!c.buttonClicked}" />

    <ui:outputText value="Current Count"/>
    <ui:outputNumber value="{!v.currentCount}"/>                                    


</aura:component>

JS Controller

({
    buttonClicked : function(component, event, helper) {
        console.log("button clicked");
        var action = component.get("c.IncrementCount");

        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {

                //initialize type of account and claim type 
                var splitcount = response.getReturnValue();
                console.log("count");
                console.log(splitcount);                                                        
                component.set("v.currentCount", response.getReturnValue());                                
            }
        });
        $A.enqueueAction(action);

    }
})

Apex Controller with Static Variable

public class LightningSampleServerController {

    public static Integer Count;

    public LightningSampleServerController()
    {

    }

    static
    {
        Count = 0;
    }

    @AuraEnabled
    public static Integer IncrementCount()
    {   
        system.debug('current count - ' + Count);
        Count++;         
        return Count;
    }       
}
8

Salesforce is a "stateless" service. Every transaction is isolated from every other transaction. This means that your static variable is discarded each time the request completes, so the counter will never get past 1. If you need the counter to be persistent across transactions, you'd have to use either a custom setting, the platform cache, or send the state back to the server by way of method parameters.

Visualforce uses client-side view state in order to give the appearance of having continuity on the server, but the state and code is loaded each time a postback occurs; you can read more at Order of Execution for Visualforce Page Postback Requests. You'll notice how the first step on a post back is to "decode view state", and the last step is to "send HTML back to the browser."

Lightning doesn't make any arrangement to automatically pass state between the server and client, unlike Visualforce. This makes Lightning much faster in normal situations, because there's no coding/decoding of large structures every time any little request is made, and also reduces bandwidth usage on mobile devices, since the entire state isn't transferred each time. It also passes back plain JSON instead of HTML, which further reduces the bandwidth of each request.

| improve this answer | |
  • I can achieve this by using visualforce and the view state support. I am trying to understand how it is different in lightning ? When you mentioned "stateless" are you referring to lightning architecture ? Is Apex server component created only once when Lightning Component is initialized or is the Apex server component created for every AuraEnabled method call ? – apn Dec 23 '16 at 0:07
  • 1
    @apn I added an edit. Visualforce's "state" is still a client-side mechanism; the program doesn't remain running while the page is loaded on the screen. I also included a link that explains how Visualforce does this. Lightning doesn't transfer the entire client state each time, which reduces server CPU time and bandwidth use, which is why it's usually much faster than the equivalent Visualforce page. – sfdcfox Dec 23 '16 at 0:18
  • @apn If you want to understand a little more about what is state and view state in Visualforce, you can refer to my post: sfdcinpractice.com/index.php/2016/12/05/view-state-visualforce . Lightning components is stateless so it doesn't support that. – Lance Shi Dec 23 '16 at 0:26

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.