- Salesforce Development Posts by Matt Lacey

Storing State in a Lightning JavaScript Controller

Posted 2017-05-17

Lighting is growing on me, both from the point of view of the UI (it genuinely improves massively with each release) and from the developer aspect. There's a lot about it that still feels overly verbose and restrictive compared to the wider JavaScript ecosystem, but I accept that's largely down to the requirements of providing a robust and secure enterprise level platform.

That said, I still find it annoying that the defacto way to deal with a components' state is to represent it through <aura:attribute> tags, you can't set objects to be properties of the controller, so what other options are there?

Use A Single Attribute

You can leverage a single attribute of type 'Object':

<aura:attribute name="state" type="Object"/>

This is relatively simple but does mean that it can be a little verbose to set a property for instance:

var state = component.get('v.state');
state.someProperty = 'this is a bit verbose';
component.set('v.state', state);

Not only that I have run into issues with code trying to access the state object before it's been initiated (in an init method!).

Use The Helper

If you've ever tried to do this in your component's controller:

someMethod: function()

You'll know that the server will reject it, but it turns out you can do this inside of the helper. It's not ideal (but then neither is the whole 'helper' mechanism), but it is a little cleaner.

Simply do this at the top of your helper file:

 state :
  thisWorks: true

and then you can access it anywhere you have a reference to the helper, i.e. all of your controller methods via the helper parameter, and inside your helper methods by using this (though the usual JavaScript caveats apply there). Now setting and reading properties is far easier, and you don't need any XML clutter.

helper.state.someProperty = 'this is less verbose';