I have developed an lwc which will trigger an apex call/display a toast message when a Platform event notification is received from the server.
I am following steps mentioned here: https://developer.salesforce.com/docs/component-library/bundle/lightning-emp-api/documentation
// Handles subscription
handleSubscribe() {
// Callback invoked whenever a new event message is received
const messageCallback = function(response) {
var obj = JSON.parse(JSON.stringify(response));
const event = new ShowToastEvent({
title: 'Congrats!!',
message: obj.data.payload.Message__c,
variant: 'success',
});
this.dispatchEvent(event);
console.log('Execution Point');
};
// Invoke subscribe method of empApi. Pass reference to messageCallback
subscribe('/event/Asset_Change_Event__e', -1, messageCallback).then(response => {
// Response contains the subscription information on subscribe call
console.log('Subscription request sent to: ', JSON.stringify(response.channel));
this.subscription = response;
});
}
I am able to print a simple log inside message callback [ I have already imported ShowToastEvent from Salesforce library]. However, if I try to show a toast message or try to call apex, it's not working.
Really appreciate your time to go through the details.
Please let me know if you have any idea what I am missing here.
Thank You.
this
context is lost inside messagecallback function and it generates an error while dispatching the event. Try binding the this context in by changing fourth last line tosubscribe('/event/Asset_Change_Event__e', -1, messageCallback.bind(this)).then(response => {