3

I have a lightning component that renders on a VF Page using lightning out. Within lightning component, I have a dropdown list that contains 3 values : A, B, C. Question is: When user selects any values from dropdown say 'B', I need to set this value in cookie. Now next time when this VF Page is loaded i need to read this cookie to check which dropdown was selected previously and the same needs to be set on the lightning component. How can we achieve this?

  • I assume cookies are protected somewhat in lightning, why not use a lightweight custom object to track the values? Has the added advantage of being cross-browser & cross-platform. – battery.cord Apr 5 '18 at 14:01
10

I recommend that you use Storage instead. I've written an example of a Value Provider that does this that you can use as a drop-in replacement. This API lets you store several megabytes of data, persists as long as a session does, and works more or less automatically.

Here's the relevant code from the other answer.

myComponentController.js

({
    init: function(component, event, helper) {
        component.addValueProvider(
            'storage',
            {
                get: function(key, comp) {
                    return sessionStorage.getItem(key);
                },
                set: function(key, value, comp) {
                    sessionStorage.setItem(key, value);
                }
            }
        );
    }
})

myComponent.cmp

<aura:component >
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <ui:inputText value="{!storage.value}" />
</aura:component>

Here, we define a Value Provider called "storage". Anything you bind to will automatically store and retrieve data from sessionStorage, even if the page is reloaded, or navigated away from and returned to later.

  • Thank you for your quick response.. Basically my VF Page has lightning component in it. And this VF Page opens in service console in a primary tab. So when I close the tab and re-invoke this VF Page does this session storage retains its saved value? – Shrey Apr 5 '18 at 20:23
  • @Shrey Yes, it should work. I haven't played with Lightning out, but it should work just the same. – sfdcfox Apr 5 '18 at 20:44
  • I tried session storage approach as you suggested, however when I close the VF Page and re-invoke it, it does not retain the value. So I tried of local storage (instead of session storage) and the value is retained. Can you please help me out here if it is ok to use local storage here? Also does the value gets cleared out when session is re-established? – Shrey Apr 5 '18 at 21:06
  • @Shrey It might be a side effect of Lightning Out. But yes, localStorage should also work for your purposes. – sfdcfox Apr 5 '18 at 21:14

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.