Lightning Web Components – Fix sessionStorage/localStorage Not Working with NavigationMixin

lightning-web-componentslwrnavigationmixin.navigatesessionstorage

I'm building a community on LWR. I would like to share information between 2 pages through sessionStorage.

Page1

handleSelection(event){
   this.selectedContactId = event.target.dataset.id;
   sessionStorage.setItem("selectedContact", this.selectedContactId);
   this[NavigationMixin.Navigate]({
       type: "comm__namedPage",
       attributes: {
           name: "Dashboard__c"
        }
    });
 }

Page2

connectedCallback(){
   console.log(sessionStorage.getItem("selectedContact"));
  //output: null
}

Observations

  1. NavigateMixin redirect well from Page1 to Page2, however the sessionStorage is always returning null value
  2. If I refresh page2 manually sessionStorage works and return the right value.

Workaround

I am using window.open("./dashboard","_self");

but I would really like to use NavigationMixin which does a smoother transition between pages.

Best Answer

I was facing the same issue. I need to open a refreshed tab whether I open it directly or through Navigation Mixin from another tab. I tried getting values from session storage in constructor, renderedCallback and connectedCallback but these functions does not called/run when we move back and forth between the tabs or when we use Navigation Mixin and didn't prefer to use window.open

So, I tried using CurrentPageReference and it resolved all of my problem.

Whether I am opening tab directly or by using Navigation Mixin, its getting correct session storage values.

You need to just import this:

import { CurrentPageReference } from 'lightning/navigation';

then write code like this:

@wire(CurrentPageReference)
    getStateParameters(currentPageReference) {
        if (currentPageReference) { 
            this.urlStateParameters = currentPageReference.state;
            if(Object.keys(this.urlStateParameters).length === 0) {
                if(sessionStorage.getItem('anyvalue')) {
                    this.yourvariable = sessionStorage.getItem('anyvalue');
                }
            }
        }
    }

Hope this solution will help you also.

Related Topic