Strategies For Sharing State Across Multiple Sharepoint Web Parts

The Problem of Isolated Web Parts

SharePoint pages allow the placement of multiple independent web parts to enable modular page composition. However, these web parts often operate in isolation, unable to directly share data or state between one another. This limitation restricts the development of integrated solutions and advanced customizations using multiple coordinated web parts on a single page.

Understanding the available options for sharing state and data across SharePoint web parts is the key to unlocking more seamless integrations and building robust, interactive pages supporting complex business solutions.

Strategies for Sharing State

There are several strategies that can facilitate web part integrations by enabling different methods of persistent and temporary state sharing:

  • Using Query Strings and URL Parameters
  • Passing Data with Session Storage
  • Leveraging SharePoint Context
  • Integrating with the Page Context Service
  • Storing Data in Custom Database Tables

The best approach depends on factors like the complexity of data being shared, the desired persistence across page loads, the level of integration between the web parts, and how modular or reusable the web part component needs to remain.

Simple Data Sharing With Query Strings

One straightforward way to achieve basic web part data sharing is by appending parameterized data to the page URL through query strings.

This method allows web parts to read and react to URL parameters that may be populated by user selections or configurations in other web parts on the page. The approach is simple to implement but only suitable for sharing simpler data.

Example Using URL Parameters to Filter Web Part Data

Consider an example page with two web parts – a Category Filters web part and a Knowledge Base Search Results web part. The filters part allows selecting categories to narrow search results. This can be integrated by having the filters part populate a URL parameter that the results part reads to query the appropriate articles.

The category filters web part would append the selected value to the URL on change, for example adding “?category=collaboration” to the page URL when selecting Collaboration as the category.

The knowledge search results web part code would check the URL parameter on loading and apply it to filter the displayed search results. This enables coordinating the two parts without complex integration.

Unlocking Powerful Integrations with Session Storage

A more versatile mechanism for sharing state across SharePoint web parts on a page is via session storage.

Session storage allows serializable data to be stored temporarily in the browser session. All web parts on the page can read and write to the same session storage.

This facilitates complex integrations between web parts, with one part able to save rich state data that other parts on the page can read to synchronize their configurations or content.

Sample Code for Writing and Reading Session Storage

Session storage follows a simple key-value model. One web part can save state data using a unique key, for example:

window.sessionStorage.setItem('filterCriteria', JSON.stringify(criteria));

Another web part can then access the stored data by asking for that key:

 
let criteria = JSON.parse(window.sessionStorage.getItem('filterCriteria')); 

By coordinating keys, complex state can be synchronized across multiple non-isolated web parts on a page.

Bridging Web Parts by Utilizing SharePoint Context

The SharePoint client-side web part programming model provides context objects that can also facilitate web part integrations in some scenarios. Specifically, the ClientSideComponentProperties context allows web parts to access parameterized configuration data.

This enables declarative data sharing by defining web part parameters and having other parts pass values for those parameters. The receiving web part can respond and synchronize with the passed contextual data.

Example of Using Context for Dynamic Web Part Configurations

Consider a web part showing employee information. It could define a “department” parameter to filter the displayed employees by department.

Another web part allows selecting a department. It can dynamically pass this selected value through the context to the employee web part’s “department” parameter.

The employee web part will react to changes in this parameter and update accordingly. This bridges the two parts without code changes or complex integration code.

The Page Context Service for Seamless Web Part Data Sharing

For more centralized and decoupled data sharing across page web parts, the SharePoint Framework Page Context Service can be leveraged. This provides an extendable dictionary stored in session storage that all web parts can access.

Web parts implement provider and consumer interfaces to get or set context data used by other parts. This mediates sharing through a centralized page state service instead of direct web part integrations.

Code Demonstration of Implementing Context Service

To save state data to the context, a web part implements the provider interface:

import {PageContext} from '@microsoft/sp-page-context';

export interface IFiltersData {

  categories: string[];

}

export class FiltersWebPart implements IDataProvider {

  pageContext: PageContext;

  // Save filters state 
  public saveFilters(filters: IFiltersData) {
    
    this.pageContext.writing(() => {  
     
      this.pageContext.set("filters", filters);
    
    });
  
  }

}  

Another web part can then get this data by consuming it:

import {PageContext} from '@microsoft/sp-page-context';

export class ResultsWebPart implements IDataConsumer {

  pageContext: PageContext;

  // Get saved filters  
  public getFilters() {
  
    return this.pageContext.consuming(context => {
    
      return context.page.filters;
    
    });
  
  }

}

This mediates state sharing through the common page context backed by the context service.

Persisting Data Across Page Loads with Custom Tables

If web parts need to persist state across page loads, one option is to save the data to custom storage tables in the site collection. This allows web parts to load and save state to enable continuity of configurations and selections beyond a single visit.

Sample Table Schema and Insertion Code for Web Part State

A web part could create a custom table to store state using a schema like:


CREATE TABLE WebPartState (
    ID int PRIMARY KEY IDENTITY(1,1),
    Key varchar(100),
    WebPartID varchar(200),
    StateData nvarchar(max)
)

It would then use SQL inserts to persist state on save, for example when leaving the page:

let sql = `INSERT INTO WebPartState (Key, WebPartID, StateData) VALUES ('filters','${wpInstanceId}', '${JSON.stringify(filtersData)}');`; 
  
await sp.web.getStorageEntity('SPSite').executeQuery(sql);

And SQL selects to restore state when loading the web part:

  
let sql = `SELECT * FROM WebPartState WHERE WebPartID = '${wpInstanceId}'`;

let stateResult = await sp.web.getStorageEntity('SPSite').executeQuery(sql);

let storedFilters = JSON.parse(stateResult.StateData); 

Enabling this persistence of custom web part data can improve continuity across visits.

Summary

There are several options available for sharing state and enabling better integrations between web parts on SharePoint pages, including:

  • URL query parameters
  • Browser session storage
  • SharePoint web part context
  • A centralized page context service
  • Custom database tables

The optimal approach depends on the specific complexity, performance needs, desired persistence, and degree of web part coupling for the integration goals.

Unlocking connections and state sharing between isolated web parts is key to creating seamless, coordinated pages supporting complex scenarios and custom solutions on SharePoint.

Leave a Reply

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