0

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.

2
  • It looks like the 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 to subscribe('/event/Asset_Change_Event__e', -1, messageCallback.bind(this)).then(response => { – manjit5190 Sep 13 '20 at 17:47
  • Thanks, @manjit5190. It's working now. If you can add that as an answer, I will accept – Salesforce Development Sep 13 '20 at 18:26
1

It looks like the this context is lost inside messagecallback function and it generates an error while dispatching the event.

Try binding the this context by changing to subscribe('/event/Asset_Change_Event__e', -1, messageCallback.bind(this)).then(response => {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.