top of page

Exchange data between LWC with pubsub

You are working with custom object development in Salesforce and you have several Lightning Web Components on the same Lightning page which do not have a parent to child relationship and these components need to share data.


How do you share and exchange data between two LWC on the same Lightning page that do not have a parent to child relationship?


This is when you can use pubsub.


First step, you will need to download the code here and place in your org.


Create a new LWC with only two components:

  • pubsub.js

  • pubsub.js-meta.xml





Do not expose pubsub, as you will not place this LWC on your Lightning page.


Second step: you need to define an event publisher. This is the LWC that is the source of the shared data and that triggers an event.


Import the pubsub into the Publisher.


import { fireEvent } from 'c/pubsub'; import { CurrentPageReference } from 'lightning/navigation'; export default class EventPublisher extends LightningElement { @api recordId; @api objectApiName; // required for pubsub: @wire(CurrentPageReference) pageRef; @track exposedData;


changeData(event) { this.exposedData = event.target.value; } handleChangeData(){ console.log("Button has been pressed--->" + this.exposedStage); fireEvent(this.pageRef,"exposeData",this.exposedData); }


In the above example, press of a button on the Publisher's HTML code triggers the event to publish the "exposedData".


Third step: you need a listener. Basically one or more other LWC that are listening to the Publisher's event.


Import the pubsub into the Listener LWC.


// Required for pubsub: import { registerListener, unregisterAllListeners } from 'c/pubsub'; import { CurrentPageReference } from 'lightning/navigation';


export default class TestListener extends LightningElement { @api recordId; @api objectApiName; @wire(CurrentPageReference) pageRef; @track exposedData; connectedCallback() { registerListener('exposeData', this.handleNewChangedData, this); } disconnectedCallback() { unregisterAllListeners(this); } handleNewChangedData(newChangedData){ this.exposedData = newChangedData; }


So, the listener is capturing the new "exposedData" coming from the publisher and storing it in the exposedData variable.


You can then either use this data in any type of manipulation or simply display it on the Listener LWC.


Example Listener HTML


<template> Changed DATA from PUBLISHER: {exposedData} <br /> </template>


I hope this was helpful and do contact if you have any questions.


Happy coding!


4 views
bottom of page