Pass Data between Components using Events in Lightning Web Components

In our Last post we checked how we can fetch data from Apex in Lightning Web Components (LWC). In this post how we can pass data between components using events in Lightning Web Component. In Lightning We have two way binding, in which if value of attribute is changed in child component then that is also reflect in parent component. But Lightning Web Component (LWC) only support one way binding. So we can pass data between components using Event or can pass data from child components to parent Lightning Web Component (LWC) or Lightning Component using Events.

Lightning Web Components LWC Salesforce Lightning, Pass data between components using events.

The structure of Events in LWC is different than what we have in Lightning. We only have one type of event exist in LWC. When we create an event, we define event propagation behaviour using two properties on the event, bubbles and composed.

  • bubblesA Boolean value indicating whether the event bubbles up through the DOM or not. Defaults to false.
  • composedA Boolean value indicating whether the event can pass through the shadow boundary. Defaults to false.

Here is the basic structure of event

const selectedEvent = new CustomEvent('selected', { detail: {recordIds}, });
// Dispatches the event.
this.dispatchEvent(selectedEvent);

Here selected is the event name. While in detail we can pass the data. To capture this event in parent we follow ‘on’+eventname naming format.

<c:lwcDataTable onselected="{!c.selectedRecords}"/>
//in controller
selectedRecords : function(component, event, helper) {
        var selectRecords = event.getParam('recordIds');
        if(selectRecords != undefined) {
            component.set("v.recordIds", selectRecords);
        }
    }

So using event we can pass data from child to parent Lightning or Lightning Web Components. Now from here we can pass this to another component using attribute or we can call child component method as well if both components are LWC components.

There are three ways in which we can use bubble and compose attribute.

  • bubbles: false and composed: false (default)
  • bubbles: true and composed: false
  • bubbles: true and composed: true

You can read about them in detail here.

Pass data between components using Pubsub module

To communicate between components that aren’t in the same DOM tree, we use a singleton library that follows the publish-subscribe pattern.
In a publish-subscribe pattern, one component publishes an event. Other components subscribe to receive and handle the event. Every component that subscribes to the event receives the event. Salesforce provide us pubsub module to us which we can use to add two components to a Lightning page in Lightning App Builder and pass Event between them.

First we need to import Pubsub module and related method.

import { NavigationMixin, CurrentPageReference } from 'lightning/navigation';
import { fireEvent } from 'c/pubsub';

These imports are required to publish events across sibling components in a Lightning page. The first one adds an adapter that lets us retrieve the current page reference, and the second is a helper function that lets us fire events across the page.

@wire(CurrentPageReference) pageRef;
fireEvent(this.pageRef, 'EventName', result.data);

We retrieve the current page reference and store it in a pageRef property. We use the custom fireEvent function that we imported earlier to fire this event across the whole Lightning page identified by pageRef.

Then in the receiver component, first we import the methods.

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

and then in controller we declare these two methods.

@wire(CurrentPageReference) pageRef; // Required by pubsub
connectedCallback() {
	// subscribe to bearListUpdate event
	registerListener('eventName', this.MethodName, this);
}
disconnectedCallback() {
	// unsubscribe from bearListUpdate event
	unregisterAllListeners(this);
}
MethodName(data) {
    //processing
}

We implemented two component lifecycle hook functions: connectedCallback and disconnectedCallback. These are automatically called when the component loads and unloads. We use these two functions to register and unregister from our custom event.

So Now we can easily pass data from child to parent component or communicate between component which are not part of same dom. You can also check a working example here.

Did you like the post or have any question, let me know in comments. happy programming 🙂

Advertisements

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.