Sub topic 7
Subscribing and handling messages in an LWC
This chapter assumes you can write a basic Lightning web component and use @wire. You should also know the connectedCallback and disconnectedCallback hooks. The message channel RecordSelected from the previous chapters must already be deployed. A publisher component that sends { recordId } on that channel must be on the same Lightning page.
What subscribing does
A publisher sends a message to a channel. A subscriber registers a function with that channel, and Lightning Message Service (LMS) calls the function each time a message arrives. The publisher never knows who is listening. The subscriber never knows who sent the message. The channel's fields are the only contract between them.
The subscribe function comes from lightning/messageService. It takes four arguments:
| Argument | Purpose |
|---|---|
| `messageContext` | The object from `@wire(MessageContext)` that tells LMS which component is subscribing. |
| `messageChannel` | The channel imported from `@salesforce/messageChannel/RecordSelected__c`. |
| `listener` | The function LMS calls with each message payload. |
| `subscriberOptions` | Optional. Currently used to set `scope`. |
It returns a subscription object. Keep that object, because unsubscribe needs it later.
A complete subscriber
The component below shows the selected record's Id. It uses the same wiring pattern as the publisher in the previous chapter.
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) {
if (message && message.recordId) {
this.selectedId = message.recordId;
}
}
get hasSelection() {
return this.selectedId !== undefined;
}
}The template reads the field. Because selectedId is a class field, a change to it rerenders the template.
<template>
<lightning-card title="Record detail" icon-name="standard:record">
<div class="slds-var-p-around_medium">
<template lwc:if={hasSelection}>
<p>Selected record Id: {selectedId}</p>
</template>
<template lwc:else>
<p>Select a record in the list.</p>
</template>
</div>
</lightning-card>
</template>Deploy the component and add it to a Lightning page next to the publisher. Click a row in the list, and the detail card updates with the Id.
Where the subscribe call goes
Subscribe in connectedCallback, as shown. The wire service provides messageContext before this hook runs, so the value is ready by then. Do not call subscribe in the constructor, because the wired value is not available there yet.
The if (!this.subscription) guard matters. A component can be removed and reinserted, or its connectedCallback can run again. Without the guard, you could end up with two subscriptions, and every message would be handled twice. The next chapter covers cleanup in detail. For now, remember that every subscribe needs a matching unsubscribe in disconnectedCallback.
The listener and `this`
LMS calls your listener as a plain function. It does not call it as a method of your component. If you pass this.handleMessage directly, this inside the handler is not your component, and the assignment to this.selectedId fails or does nothing.
There are two safe patterns:
// Pattern 1: arrow function wrapper, as in the full example
subscribe(this.messageContext, RECORD_SELECTED, (message) => this.handleMessage(message));
// Pattern 2: bind once
subscribe(this.messageContext, RECORD_SELECTED, this.handleMessage.bind(this));Both work. The arrow function is more common in Salesforce samples, and it is easy to read.
Handling the payload
The listener receives one argument, the payload object that the publisher sent. Its keys match the field names in the channel metadata. For RecordSelected, the only key is recordId.
Treat the payload as untrusted input from the subscriber's point of view. Another developer can publish to your channel, and a publisher can send a payload with missing fields. Check for what you need before you use it:
handleMessage(message) {
if (!message || !message.recordId) {
return;
}
this.selectedId = message.recordId;
}Keep the handler short. A good handler validates the payload, copies the values it needs into component fields, and returns. If you need to load data, call the wired or imperative Apex method from a separate method. Do the same for any other slow work.
Do not modify the payload object. Several subscribers can receive the same message, and you should not assume each one gets its own copy.
Reacting to the message in the UI
You have three common choices for what the handler does:
- Set a field. The template rerenders. This is the simplest option and covers most cases.
- Change a parameter that a wire adapter uses. For example, set
this.recordId, and a@wire(getRecord, { recordId: '$recordId' })re-provisions its data. - Call an imperative method, such as an Apex call or a
refreshApex.
For the second choice, the wired parameter must be reactive, which means it is a $-prefixed property of the class. A plain field that you read inside the wire config will not trigger a reload.
What a subscriber does not get
LMS delivers messages only to subscriptions that exist at the moment of publishing. It has no memory.
- A component that subscribes after a message was published does not receive that message.
- If the user selects a record before the detail component has loaded, the detail component starts blank.
- Messages are not saved between page loads.
If late-loading subscribers must know the current state, store the state somewhere they can read it. Examples are a record page, a URL parameter, or an Apex-backed value. Use the message only to announce changes.
LMS also makes no promise about the order in which several subscribers are called. Do not write one subscriber that depends on another subscriber having already run.
Scope in one paragraph
The { scope: APPLICATION_SCOPE } option tells LMS to deliver messages from anywhere in the application. Without the option, the subscription uses the default scope. The default delivers only when the subscriber is in the active area of the page, for example the active tab in a Lightning console app. The scope chapter explains the difference. If your subscriber sits on the same page as the publisher in a standard app and works, you may not notice a difference. The difference shows up in console apps with several tabs.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Handler runs but `this.selectedId` never changes the UI | The listener was passed unbound, so `this` is wrong | Use an arrow function or `.bind(this)` |
| Error that the message context is undefined | `subscribe` was called in the constructor, or the `@wire(MessageContext)` property is missing | Move the call to `connectedCallback`, and declare the wire |
| Nothing is received on a console page | Default scope, and the subscriber is not in the active tab | Pass `{ scope: APPLICATION_SCOPE }` |
| Handler runs twice for one message | `subscribe` ran twice with no `unsubscribe` | Guard with `if (!this.subscription)`, and unsubscribe on disconnect |
| `message.recordId` is `undefined` | Field name in the publisher does not match the channel, or the publisher sent no payload | Check the channel metadata and validate in the handler |
| Import error for the channel | Channel is not deployed, or the name lacks the `__c` suffix | Deploy the channel, and import `RecordSelected__c` |
Testing it by hand
- Deploy the channel, the publisher, and the subscriber.
- Open the Lightning App Builder and place both components on one page.
- Open the page and click a row in the list. The card should show the Id.
- Add a
console.log(JSON.stringify(message))line at the top ofhandleMessageand open the browser developer tools. Click several rows and confirm one log line appears per click. Two lines per click point to a duplicate subscription.
Remove the log line before you deploy to production.
Exercise
A teammate writes subscribe(this.messageContext, RECORD_SELECTED, this.handleMessage) in connectedCallback. The handler runs when a message is published, but the card never updates and the console shows an error about reading selectedId. What is wrong, and how do you fix it?
Show answer
LMS calls the listener as a plain function, so this inside handleMessage is not the component. Wrap the call in an arrow function, (message) => this.handleMessage(message), or pass this.handleMessage.bind(this).
Exercise
A subscriber component is placed on a page that is already open. A user selected a record before the component was added. Why does the component show nothing, and what would you use to give it the current selection?
Show answer
LMS only delivers messages to subscriptions that exist when publish is called, and it does not replay earlier messages. To give a late subscriber the current state, keep the state somewhere it can read on load, such as a record page value, a URL parameter, or data loaded from Apex. Use the message only to announce later changes.