[SalesForce] lightning navigation pass parameters in URL

on my custom community page, using a Lighting web component and navigating to a different page by passing some query string in URL, problem is the unable to refer Javascript variable in below code snippet:

let keyVal;
let val;
// here this.params is having a value like "tabset=e2571"

if(this.params && this.params.split('=').length === 2){
  keyVal = this.params.split('=')[0];
  val = this.params.split('=')[1];
}

this[NavigationMixin.Navigate]({
  type: 'comm__namedPage',
  attributes: {
    pageName: 'samplePage'

  },
  state: {
    keyVal : val
  }
});

This code is not able to refer the value of keyVal variable and ended up to generate below URL:
Actual URL:
https://xxxx.cs151.force.com/xxxxx/s/samplePage?keyVal=e2571

Expected URL
https://xxxx.cs151.force.com/xxxxx/s/samplePage?tabset=e2571

I have already tried with replacing the variable name with c__keyVal but no luck.

Best Answer

This is because when you declare a state object like this:

state: {
    keyVal : val
  }

you do not use keyVal variable, you just declare a new property of the state object.

One of possible solutions would be to create an object and assign its properties like this:

var obj = {};
obj[keyVal] = val;

and then you can assign this object to the state object:

this[NavigationMixin.Navigate]({
  type: 'comm__namedPage',
  attributes: {
    pageName: 'samplePage'

  },
  state: obj
});