Get and Set localStorage variable in Salesforce Lightning Web Component

Get and Set localStorage variable in Salesforce Lightning Web Component

localStorage.setItem() and localStorage.getItem() can be used to Get and Set localStorage variable in Salesforce Lightning Web Component.

Sample Lightning Web Component:

HTML:

<template>
    <lightning-card>
        <div class="slds-var-p-around_medium">
        {strValue}
        </div>
    </lightning-card>
</template>

JavaScript:

import { LightningElement } from 'lwc';

export default class sampleLightningWebComponent extends LightningElement {

    strValue;

    constructor() {

        super();
        localStorage.setItem( 
            'exampleItem', 
            'Testing' 
        );
        console.log( 
            'exampleItem is', 
            localStorage.getItem( 
                'exampleItem' 
            ) 
        );
        this.strValue = localStorage.getItem( 
            'exampleItem' 
        );

    }

}

js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>58.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Output:

Leave a Reply