0

I am trying to publish a message form lWC , but getting error as below:

lightning/messageService: invalid message context]

i have created the message channel file added it in the package.xml and deployed it to the org, below is my codes not sure any mistake i am making. below is my code :

LMS MetaFile:

    <?xml version="1.0" encoding="UTF-8"?>
            <fieldName>messageText</fieldName>
    <LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
        <masterLabel>SampleMessageChannel</masterLabel>
        <isExposed>true</isExposed>
        <lightningMessageFields>
            <description>Holds the message to display</description>
        </lightningMessageFields>
    </LightningMessageChannel>

LWC Code

import { LightningElement, wire } from 'lwc';
import messageChannel from '@salesforce/messageChannel/Sample__c';
import {publish, MessageContext} from 'lightning/messageService'
export default class Publisher extends LightningElement {
    @wire(MessageContext)
    messageContext;
    handleButtonClick() {
        let message = {messageText: 'This is a test'};
        publish(this.messageContext, messageChannel, message);
    }
}
5
  • 2
    A doubt, is the LMS metafile missing a fieldName or have you forgotten it to put it in code above? I see only description. Second why are you importing Sample__c when you have deployed SampleMessageChannel Commented Nov 26, 2020 at 16:26
  • @NagendraSingh I think that is the answer! Commented Nov 26, 2020 at 16:27
  • sorry filed name is present at the top...
    – dumitry
    Commented Nov 26, 2020 at 17:15
  • <fieldName>messageText</fieldName>
    – dumitry
    Commented Nov 26, 2020 at 17:16
  • okay, but it is outside of the LightningMessageChannel Commented Jan 31 at 7:34

1 Answer 1

0

The fieldName tag need to be inside the LightningMessageChannel tag. Like below

  <?xml version="1.0" encoding="UTF-8"?>
    <LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
        <fieldName>messageText</fieldName>
        <masterLabel>SampleMessageChannel</masterLabel>
        <isExposed>true</isExposed>
        <lightningMessageFields>
            <description>Holds the message to display</description>
        </lightningMessageFields>
    </LightningMessageChannel>

but there is still one more problem as stated by
@Nagendra Singh - the import needs to be for SampleMessageChannel

import { LightningElement, wire } from 'lwc';
import messageChannel from '@salesforce/messageChannel/SampleMessageChannel__c';
import {publish, MessageContext} from 'lightning/messageService'
export default class Publisher extends LightningElement {
    @wire(MessageContext)
    messageContext;
    handleButtonClick() {
        let message = {messageText: 'This is a test'};
        publish(this.messageContext, messageChannel, message);
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .