Sub topic 9
State, list views, and default field values
This chapter covers the state property of a page reference. It assumes you can already call this[NavigationMixin.Navigate] with a PageReference and read CurrentPageReference. You'll use state for three things: opening a specific list view, pre-filling a New record form, and passing your own parameters between pages.
What state is
A PageReference has three parts: type, attributes, and state. The type and attributes identify the page. The state is an optional object of extra parameters that changes how the page behaves without changing which page it is.
Salesforce serializes state into the URL as query parameters. This has three consequences:
- Every value in
statemust be a string. Numbers, booleans, objects, and arrays are not supported. Convert them first, for example withString(count)orJSON.stringify(obj). - State survives a page refresh, a bookmark, and a copied link. Anything you put there is visible to the user.
- Changing state on the current page is a navigation. The browser history gets a new entry, and
CurrentPageReferenceemits a new value.
The platform reserves some state keys, such as filterName and defaultFieldValues. Keys you define yourself must start with c__, for example c__orderId. Keys without the prefix may be dropped or collide with platform keys.
Opening a list view with filterName
To show a list of records, navigate to a standard__objectPage with actionName: 'list'. The filterName state key selects the list view. It accepts either the list view's API name or its 15-character or 18-character ID. Recent is a built-in list view that exists for every object.
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class OpenAccountList extends NavigationMixin(LightningElement) {
handleRecent() {
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Account',
actionName: 'list'
},
state: {
filterName: 'Recent'
}
});
}
handleAllAccounts() {
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Account',
actionName: 'list'
},
state: {
filterName: 'AllAccounts'
}
});
}
}If you omit filterName, Salesforce opens the list view the user last viewed for that object. If the name or ID does not match a list view the user can see, the page falls back to a default list view. It does not throw an error in your component, so check the name when the result looks wrong. The API name of a custom list view is not the label shown on screen. Find it in the list view's URL or in Setup.
Pre-filling a New record form
For actionName: 'new', the defaultFieldValues state key pre-populates fields on the form. Its value must be a single string in a specific encoded format, not a plain object. The lightning/pageReferenceUtils module provides encodeDefaultFieldValues to build that string.
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';
export default class NewContactFromAccount extends NavigationMixin(LightningElement) {
@api recordId;
handleNewContact() {
const defaultValues = encodeDefaultFieldValues({
AccountId: this.recordId,
LastName: 'Unknown',
LeadSource: 'Web'
});
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Contact',
actionName: 'new'
},
state: {
defaultFieldValues: defaultValues
}
});
}
}Keep these points in mind:
- Use field API names as keys, such as
AccountIdandLeadSource. Labels do not work. - A lookup field takes the record ID as its value, as
AccountIddoes above. - A default only fills a field that is on the layout the user sees. Salesforce does not add fields to the layout for you.
- A default is a starting value. The user can edit it before saving, and validation rules still apply.
- Do not build the encoded string by hand. Characters such as commas and equals signs in values need escaping, and the utility handles that.
Passing your own state to a component page
You can also attach custom state to a page that hosts one of your components. The standard__navItemPage type targets a custom tab, and standard__namedPage targets pages such as home. Both accept state with c__ keys.
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class OpenOrderSearch extends NavigationMixin(LightningElement) {
handleSearch() {
this[NavigationMixin.Navigate]({
type: 'standard__navItemPage',
attributes: {
apiName: 'Order_Search'
},
state: {
c__status: 'Open',
c__maxRows: String(50)
}
});
}
}Order_Search stands for the API name of a custom tab that you have created for a component. Replace it with your own tab's API name.
On the destination, read the values through CurrentPageReference. The wire provides state as strings, so convert them where you need other types.
import { LightningElement, wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
export default class OrderSearch extends LightningElement {
status = 'All';
maxRows = 25;
@wire(CurrentPageReference)
handlePageRef(pageRef) {
const state = pageRef && pageRef.state ? pageRef.state : {};
this.status = state.c__status || 'All';
this.maxRows = state.c__maxRows ? parseInt(state.c__maxRows, 10) : 25;
}
}Two details in this handler matter:
pageRefcan beundefinedbefore the first value arrives, so the code guards for it.- The values are read on every emission, not only once. If the user changes the URL or another component navigates to the same page with new state, the handler runs again and the component updates.
Updating state on the current page
To change a filter without leaving the page, navigate to the current page reference with modified state. Spreading the existing reference keeps the type and attributes.
import { LightningElement, wire } from 'lwc';
import { NavigationMixin, CurrentPageReference } from 'lightning/navigation';
export default class StatusFilter extends NavigationMixin(LightningElement) {
currentPageReference;
@wire(CurrentPageReference)
setPageRef(pageRef) {
this.currentPageReference = pageRef;
}
handleStatusChange(event) {
this[NavigationMixin.Navigate]({
...this.currentPageReference,
state: {
...this.currentPageReference.state,
c__status: event.detail.value
}
});
}
}The spread of state preserves other parameters. Without it, the new state object replaces the old one and the other keys disappear.
Common errors
| Symptom | Likely cause |
|---|---|
| Custom state key is missing on the destination | The key lacks the `c__` prefix |
| Navigation fails or the value is ignored | A state value is a number, boolean, or object instead of a string |
| New form opens with no defaults | `defaultFieldValues` holds a plain object instead of the encoded string |
| A field is not pre-filled | The key is a label or the field is not on the layout |
| List view opens the wrong view | `filterName` holds the label instead of the API name or ID |
| Other filters vanish after an update | The existing `state` was not spread into the new object |
Exercise
A component must open the New Opportunity form with StageName set to Prospecting and AccountId set to the current record's ID. Which page type, action, state key, and helper do you use, and what must be true of the field keys?
Show answer
Use a standard__objectPage page reference with objectApiName: 'Opportunity' and actionName: 'new'. Put defaultFieldValues in state, with the value produced by encodeDefaultFieldValues({ StageName: 'Prospecting', AccountId: this.recordId }) from lightning/pageReferenceUtils. The keys must be field API names, and the fields must be on the layout the user sees for the defaults to show.
Exercise
You navigate to a custom tab with state: { c__page: 2 } and the value never arrives as expected. What are two problems with this code, and how do you fix them?
Show answer
First, state values must be strings, so use c__page: String(2) (or '2'). Second, on the destination, the value comes back as a string, so convert it with parseInt(pageRef.state.c__page, 10) after the CurrentPageReference wire delivers it.