Sub topic 2
Getting a MessageContext with `@wire`
Assume you know LWC classes, decorators, lifecycle hooks, and Salesforce DX deployment. This chapter assumes the RecordSelected__c message channel already exists.
Getting a `MessageContext` with `@wire`
MessageContext is the connection between an LWC and Lightning Message Service (LMS). The @wire decorator supplies it to the component. You pass this context to LMS functions such as publish and subscribe.
import { LightningElement, wire } from 'lwc';
import { MessageContext } from 'lightning/messageService';
export default class RecordList extends LightningElement {
@wire(MessageContext)
messageContext;
}The component does not create or configure this object manually. Salesforce provides the context when the component runs on a supported Lightning page.
Publishing a message from an LWC
publish sends a plain JavaScript object through a message channel. This example publishes the selected record ID when a button is clicked.
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);
}
}A template could call handleSelect from buttons that contain a record ID in data-id. publish does not return a response. Subscribers react independently.
Subscribing and handling messages in an LWC
subscribe registers a callback. The callback receives the payload published by another component.
import { LightningElement, wire } from 'lwc';
import {
subscribe,
unsubscribe,
MessageContext
} from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class RecordDetail extends LightningElement {
selectedId;
subscription;
@wire(MessageContext)
messageContext;
connectedCallback() {
this.subscription = subscribe(
this.messageContext,
RECORD_SELECTED,
(message) => {
this.selectedId = message.recordId;
}
);
}
disconnectedCallback() {
unsubscribe(this.subscription);
this.subscription = null;
}
}Store the subscription so you can remove it when the component leaves the page. This prevents stale callbacks and duplicate handling after rerendering.
Exercise
Which object must an LWC pass to both publish and subscribe?
Show answer
The MessageContext provided by the @wire(MessageContext) decorator.