Saving User Session State In Connected Sharepoint Web Parts

The Problem of Losing User Session State

Connected SharePoint web parts often lose user session state and input data on postbacks. This occurs because the web parts are reloaded on each request, clearing any context and inputs provided by the user. For example, parameters like filters, search terms, pagination, and more will be forgotten between page loads.

Losing this session state leads to a poor user experience. Users must re-enter any filters, searches, or other context every time they interact with a web part. The loss of context also impacts connected web parts that are filtering or displaying related data. Without persisted session state, connected web parts lose synchronization on postbacks.

Examples of Functionality Impacted

  • Filters – Applied filters are lost and must be reselected
  • Searches – Previously entered search terms are cleared
  • Pagination – Web parts revert back to the first page
  • Dependent Filters – Connected web parts lose context of applied filters
  • Dependent Lookups – Loss of selected keys for lookup values

In these examples, the user experience degrades significantly. Users must reapply filters, redo searches, and re-paginate the datasets. Connected web parts become decoupled due to the loss of session state.

Strategies to Maintain Session State

Several strategies exist to persist user session state across page loads for SharePoint Framework web parts:

  • Browser Storage – Save session state into local storage or cookies
  • URL State – Pass transient parameters in the page URL
  • Form State – Embed state as hidden form fields

Each approach has advantages and limitations. Choosing the right persistence strategy depends on context like page requirements, browser support, data sensitivity and more.

Using Browser Storage to Persist Data

Browser storage like local storage and cookies offer client-side persistence for web apps. Values can be stored per user, across sessions, without server interaction. Modern browsers provide APIs to save keyed data objects.

Local browser storage is useful for persisting user session state in SharePoint web parts. Filters, searches, pagination and other context can be saved during use. The stored values are then reloaded to recreate the previous state on initialization.

Passing Data in URLs and Forms

User session state can also be maintained by passing data between requests. URL query parameters, hidden form fields and headers provide communication channels to send information as pages load.

Complex objects can be serialized to strings when embedding in URLs or forms. Client-side code can then parse the strings back into objects. However, size limits apply when sending data over requests.

Using Browser Cookies

Browser cookies offer another storage option for persisting user context. Small amounts of string data can be saved via document.cookie APIs. Cookies travel in HTTP headers so state is maintained across browser requests.

The main advantage of cookies is broad browser support. However, capacity limits apply to the amount of data saved. User security and privacy settings may also block cookie usage.

Implementing Local Storage in SharePoint Framework

For a responsive user experience, the SharePoint Framework offers robust support to save session state into local browser storage. Values can persist across pages without costly server interaction.

Introduction to the LocalStorage API

The LocalStorage API provides web storage maintaining key/value pairs within the user’s browser. The stored objects persist across sessions closing, allowing web apps to cache client context.

Common operations like getItem, setItem and removeItem manipulate the localStorage values. Limits exist per domain on the amount of data saved in localStorage browsers, typically at least 5MB.

Saving Web Part Configuration

A key use case for localStorage is persisting SharePoint web part configuration. As users customize filters, searches, settings and more, these values can be saved into localStorage.

On web part initialization, saved configuration can be loaded from localStorage and reapplied. This restores the state without user reentry improving the connected web part UX.

Restoring Previous State on Initialization

LocalStorage state can recreate session context through the web part lifecycle. During initialization, values are loaded from storage and rehydrated into objects. These persistent settings are then applied to restore previous state.

This lifecycle integration ensures context like filters, searches, pagination and more persist seamlessly across sessions. Connected web parts also stay in sync as dependencies reload shared state values.

Code Examples

Below find sample code showing patterns to save user session state with local storage in SharePoint Framework web parts.

Saving Filter, Search, and Pagination Values

  // Save applied filters
  const filters = this.filterPanel.getAppliedFilters();
  localStorage.setItem('filters', JSON.stringify(filters));

  // Save current search query 
  const searchQuery = this.searchBox.value;
  localStorage.setItem('searchQuery', searchQuery);

  // Save current pagination states
  const page = this.paginator.getCurrentPage();
  localStorage.setItem('page', page); 

Restoring Previous Values on Initialization

  // Load filters from localStorage
  const lsFilters = localStorage.getItem('filters');
  if (lsFilters) {
    const filters = JSON.parse(lsFilters);
    this.filterPanel.applyStoredFilters(filters); 
  }

  // Load previous search query
  const searchQuery = localStorage.getItem('searchQuery');
  if (searchQuery) {
    this.searchBox.value = searchQuery;
    this.search(); // Init search automatically
  }
  
  // Load pagination state
  cons page = localStorage.getItem('page');
  if (page) {
    this.paginator.setPage(page); 
  }

Walkthrough: Adding Local Storage to a Web Part

Follow these steps to enable browser storage in a custom SharePoint Framework web part:

  1. Add localStorage type imports
  2.     import { WebPartContext } from '@microsoft/sp-webpart-base';  
        import { localStorage } from '../Utilities';
      
  3. Define interface properties for stored state
  4.     export interface IMyWebPartState {
          filters: string[];
          page: number; 
        }
      
  5. Load saved state during web part init
  6.     public async init(context: WebPartContext): Promise {
          const cachedState = localStorage.getItem('myWebPartState');
          if (cachedState) {
            // Apply filters, pagination, etc
          }
        }
      
  7. Persist user changes with lifecycle hooks
  8.     public onAfterFilterApplied(filters: string[]) { 
          localStorage.setItem('myWebPartState', {
            filters,
            page: this.paginator.page
          });
        }
      

With these steps, the web part state now persists locally across sessions! The user maintains context like filters between page loads.

Considerations and Alternatives

When implementing browser storage for session persistence, several considerations apply around privacy, capacity and alternatives.

Browser Storage Limitations

  • Storage Capacity – Local storage allows around 5MB per domain, cookies are more limited
  • Persistent Storage – Users may clear storage which wipes saved web part state
  • Privacy Concerns – Browser APIs can raise user trust issues around sensitive data
  • Older Browsers – Legacy browser support for web storage may be limited

Due to these factors, local storage may not suit all web part state scenarios. Alternative options like cookie fallbacks help manage browser limitations.

Alternative Options like Browser Cookies

As an alternative to localStorage, browser document.cookie storage offers wider legacy browser support. Cookies also allow manual expiration policies, clearing them when no longer needed.

However, cookie storage space is more limited compared to localStorage. Plus, users can block cookie access which would break session persistence logic.

In some cases a combined approach makes sense:

  1. First attempt localStorage to save state
  2. If saving fails, fall back to document.cookie

With this policy, web parts gracefully handle varied browser environments with state persistence.

Additional Resources

For more details on persisting user session state within SharePoint Framework client-side web parts, reference the resources below:

Leave a Reply

Your email address will not be published. Required fields are marked *