Sub topic 7
Subscribing and handling messages in an LWC
This chapter assumes you can write a basic Lightning web component and use @wire. It also assumes you know connectedCallback and disconnectedCallback, and that you have already deployed the RecordSelected message channel from the earlier chapters. Here you build the receiving side: a component that listens on the channel and reacts to each message.
What subscribing does
Subscribing registers a handler function with Lightning Message Service (LMS). When any component publishes to that channel, LMS calls your handler and passes it the payload. The publisher does not know your component exists, and you do not know who published.
The subscribe function takes four arguments:
| Argument | Purpose |
|---|---|
| `messageContext` | The `MessageContext` that identifies where your component sits on the page. |
| `messageChannel` | The channel imported from `@salesforce/messageChannel/RecordSelected__c`. |
| `listener` | The function LMS calls with each message. |
| `subscriberOptions` | Optional. Currently used to set `scope`. |
It returns a subscription object. Keep it, because you need it later to unsubscribe.
A complete subscriber
The component below shows the id of the record that was last selected.
import { LightningElement, wire } from 'lwc';
import {
subscribe,
unsubscribe,
APPLICATION_SCOPE,
MessageContext
} from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class RecordDetail extends LightningElement {
selectedId;
subscription = null;
@wire(MessageContext)
messageContext;
connectedCallback() {
if (!this.subscription) {
this.subscription = subscribe(
this.messageContext,
RECORD_SELECTED,
(message) => this.handleMessage(message),
{ scope: APPLICATION_SCOPE }
);
}
}
disconnectedCallback() {
unsubscribe(this.subscription);
this.subscription = null;
}
handleMessage(message) {
this.selectedId = message.recordId;
}
}The template needs only to display the field:
<template>
<lightning-card title="Record Detail">
<p class="slds-p-horizontal_small">Selected: {selectedId}</p>
</lightning-card>
</template>How the pieces fit together
Points to understand
- Subscribe in
connectedCallback. The@wire(MessageContext)property is available by then, so you can pass it tosubscribe. - Guard against duplicates. The
if (!this.subscription)check stops a second subscription if the component is connected again. A duplicate subscription makes the handler run twice for every message. - Use an arrow function for the listener. Writing
(message) => this.handleMessage(message)keepsthispointing at your component. Passingthis.handleMessagedirectly loses that binding, andthis.selectedIdwould fail. - Assign to a field to re-render. In LWC, class fields are reactive. Setting
this.selectedIdin the handler updates the template with no extra code. - Unsubscribe when done. The
disconnectedCallbackremoves the subscription. The next chapter covers this lifecycle in depth.
Handling the message
The listener receives the payload as a plain object. Its keys match the fields you published, so message.recordId works because the publisher sent { recordId: ... }. Treat the payload defensively. A different publisher might omit a field, so check before you use it.
handleMessage(message) {
if (message && message.recordId) {
this.selectedId = message.recordId;
}
}Common errors
- Nothing happens when a message is published. Check that the channel name in both components ends in
__cand matches the deployed metadata. Then check the scope. WithoutAPPLICATION_SCOPE, the subscriber only receives messages while its component is in the active area of the page, such as the active tab. Scope is covered in a later chapter. subscribethrows or returns nothing.messageContextmay be undefined. Make sure you callsubscribeinconnectedCallback, not in the constructor.- The handler runs more than once per message. The component subscribed several times. Keep the null check, and reset
subscriptiontonullon unsubscribe. thisis undefined in the handler. The listener was passed without an arrow function.
Exercise
A subscriber calls subscribe inside connectedCallback and passes this.handleMessage as the listener. When a message arrives, the handler fails with "Cannot set properties of undefined" on this.selectedId. What is the cause, and how do you fix it?
Show answer
Passing the method directly loses the this binding, so this is undefined when LMS calls the handler. Wrap it in an arrow function, (message) => this.handleMessage(message), so this refers to the component.
Exercise
Why does the sample subscriber check if (!this.subscription) before calling subscribe?
Show answer
A component can be connected more than once. Without the check, it would create several subscriptions and the handler would run multiple times for each published message.