Exploring Salesforce Lightning Web Components: Part 8

Wrapping up the series with a global state solution.

Image for post
Image for post

This article is part of the series starting with Exploring Salesforce Lightning Web Components: Part 1.

Borrowing from React Ecosystem

In the previous article we explored using the Salesforce provided pubsub solution. One of the challenges we observed is that it did not provide a global state solution; it is just a pub sub solution.

At the same time, in the world of React, this is an old problem with a defacto-standard solution:

A predictable state container for JavaScript apps.

— Redux — Redux

So, let us see how we can refactor the previous example with Redux. In this case, we are looking to have two sibling components, Child1 and Child2, share a common state:

Image for post
Image for post

We first update the parent component, HelloWorld:

Observations:

  • Because we cannot load third-party scripts using imports, we resort to using the precompiled version of Redux that exposes itself on the global Window object; this involves adding the JavaScript library to the staticResources folder and using the loadScript function as shown

We next update the Child1 (and Child2) components to use Redux.

Observations:

  • Without fully understanding Redux, one can generally understand the flow of this solution as it is very similar to the previous pubsub example

The core of the Redux functionality is in the store lightning web component:

Observations:

  • The getStore function ensures that we have a singular store across all the components

With this implementation, the global state persists across tabs in a Salesforce application, e.g., all the tabs in Sales.

Image for post
Image for post

Wrap Up

Interesting that through this 8 part series, we spent all of our time focusing on the general aspects of Lighting Web Components instead of the Salesforce-specific pieces; will leave that to you to learn.

On a side-note, I just happened to learn that Salesforce recently released an open-source version of Lightning Web Components. As a matter of fact, I was sufficiently intrigued that I wrote up another article on it.

Written by

Broad infrastructure, development, and soft-skill background

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store