Learn how we can apply the Pub/Sub design pattern to communicate between two micro-frontends
useEffects
to listen to changes, I just published and subscribed to some events. Luckily this was only needed less than a handful of times so the solution didn’t need to be the most robust, ultra fast, 0.002ms response time type solution.
The way I implementated that was by dispatching a CustomEvent
with my data and adding event listeners on components for this event. It meant that I didn’t need to keep a list of subscribers because addEventListener
did that for me, and I didn’t need to loop through my subscribers to push them the changes, again, addEventListener
does that for me. Have a look at the mandatory “Counter” example on Codesandbox.
I want to make a disclaimer right now. This is a very basic example, I built it without thinking too much. The chances that there is a Micro Frontend state solution is almost a 100%. If you were going to build something custom, I would probably use something like RxJS.
createSubscriptions
, this would be used to keep track of subscribers, allow things to subscribe and call a action when the subscribers need to be notified.
subscribe
: This method allows things to subscribe to and changes and accepts a callback function which will be the action that is called on publish
.publish
: Any part of the application can send out a publish event. We go through each subscriber and call their action.setCount
action, this works out because whenever the publish
is triggered it will call setCount
with the value. We also return the result of the subscribe
method which will unsubscribe the component when it unmounts.
Vue app
publish
an updated count.
To see all the code, check out this codesandbox. To play around with the result, check out the preview.
I will say with the codesandbox link, the editor preview is really wacked when using the unpkg version of the libraries. The preview link is a lot nicer.