Exploring Salesforce Lightning Web Components: Part 8
Wrapping up the series with a global state solution.
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:
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 also use the loaded flag to delay loading the child components until Redux is available
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
- Notice that handleSubscribe is implemented as a property (arrow function) instead of a method; this pattern automatically binds the function to the class
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
- The rest of the implementation is straight-up Redux
With this implementation, the global state persists across tabs in a Salesforce application, e.g., all the tabs in Sales.
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.