[SalesForce] Lightning Component – maintaining a counter in Server Controller using Static Variable

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;
    }       
}

Best Answer

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.

Related Topic