Sub topic 6
Publishing a Message from an LWC
This chapter covers the publishing side of Lightning Message Service (LMS). It assumes you can write a basic Lightning web component, use @wire and lifecycle hooks, and deploy metadata from a Salesforce DX project. It also assumes you have already created the RecordSelected message channel from the previous chapter. Subscribing is covered in the next chapter.
What publishing does
A publisher is a component that sends a message to a channel. It does not know who is listening. It hands the message to LMS, and LMS delivers it to every active subscriber on that channel that is allowed to receive it. The publisher needs three things:
- The
publishfunction fromlightning/messageService. - A
MessageContext, which tells LMS where in the page the publisher lives. - A reference to the channel, imported from
@salesforce/messageChannel.
The diagram below shows the flow of a single message.
The publisher component
import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class RecordList extends LightningElement {
@wire(MessageContext)
messageContext;
handleSelect(event) {
const payload = { recordId: event.currentTarget.dataset.id };
publish(this.messageContext, RECORD_SELECTED, payload);
}
}Walk through it line by line.
@wire(MessageContext)fillsmessageContextwith an object that identifies this component's place in the page. LMS uses it to decide which subscribers can receive the message.- The channel import ends in
__c. The metadata file is namedRecordSelected.messageChannel-meta.xml, but the import path uses the API nameRecordSelected__c. publishtakes exactly three arguments: the context, the channel, and the payload.- The payload is a plain object. Its keys should match the
fieldNamevalues declared in the channel metadata, hererecordId.
A matching template
The handler reads data-id from the clicked element, so the template must set it:
<template>
<lightning-card title="Records">
<ul class="slds-var-p-around_small">
<template for:each={records} for:item="rec">
<li key={rec.id}>
<a data-id={rec.id} onclick={handleSelect}>{rec.name}</a>
</li>
</template>
</ul>
</lightning-card>
</template>This template needs a records array on the class, for example one returned by an Apex method or a wire adapter. The data-id attribute is what event.currentTarget.dataset.id reads. Use currentTarget rather than target, because the click may land on a child element inside the link, and that child has no data-id.
Common errors
| Symptom | Likely cause |
|---|---|
| Import error for `@salesforce/messageChannel/RecordSelected__c` | The channel is not deployed to the org, or the name is missing `__c`. |
| `publish` throws or does nothing on first use | `messageContext` is not populated yet. It is wired, so it is `undefined` until the component connects. Do not call `publish` from the constructor. |
| Subscribers never fire | Subscriber is outside the publisher's scope. A subscriber using default scope only hears messages from its own part of the page. |
| `recordId` is `undefined` in the subscriber | Payload key does not match the field name, or the `data-id` attribute is missing. |
| Payload fields arrive as empty objects | The payload contained functions, class instances, or DOM nodes. Send only serializable values. |
Keep the payload simple
LMS copies the payload to each subscriber, so send identifiers and small values, not whole records or component references. A subscriber that needs record data can fetch it itself with the Id.
Exercise
Exercise
A developer calls publish(this.messageContext, RECORD_SELECTED, { recordId: id }) inside connectedCallback and sometimes nothing is delivered. What are two things to check, and what does the publish call need as its three arguments?
Show answer
The three arguments are the MessageContext, the imported message channel, and the payload object. Check that the channel is deployed and imported with its __c name, and that the wired messageContext is populated at that moment. Also check that the subscriber's scope allows it to receive messages from this publisher. Publishing from a user event handler such as handleSelect avoids the timing problem, because the context is ready by then.