+ Start a Discussion
Prabhjot Singh 27Prabhjot Singh 27 

Issue in documentation in Emp API for LWC(Lightning Web Component))

While implementing emp API in LWC to subscribe the platform event I  find out that there is small issue in sample code snipit given in documentation.
Issue is in handleSubscribe method in js below is the code given in documentation:
handleSubscribe() {
        // Callback invoked whenever a new event message is received
        const messageCallback = function(response) {
            console.log('New message received : ', JSON.stringify(response));
            // Response contains the payload of the new message received
        };

        // Invoke subscribe method of empApi. Pass reference to messageCallback
        subscribe(this.channelName, -1, messageCallback).then(response => {
            // Response contains the subscription information on successful subscribe call
            console.log('Successfully subscribed to : ', JSON.stringify(response.channel));
            this.subscription = response;
            this.toggleSubscribeButton(true);
        });
    }
 Correction is required in messageCallback method which should be as below:
const messageCallback = (response) => {
        console.log('New message received : ', JSON.stringify(response));
        this.payload = JSON.stringify(response);
        console.log('this.payload: ' + this.payload);
        // Response contains the payload of the new message received
    };
We have to use arrow function as it does not have its own scope.  
Best Answer chosen by Prabhjot Singh 27
Prabhjot Singh 27Prabhjot Singh 27
In the question it self I proposed the correct way to subscribe the event in lwc which by making small change in messageCallback method. 
const messageCallback = (response) => {
        console.log('New message received : ', JSON.stringify(response));
        this.payload = JSON.stringify(response);
        console.log('this.payload: ' + this.payload);
        // Response contains the payload of the new message received
    };

 

All Answers

Chetan Anand 13Chetan Anand 13
Excellent. Good Catch. 
Radhika DhanapalRadhika Dhanapal
Good. Useful update.
Nidhin VargheseNidhin Varghese
Good, useful information. 
Jithin ChandJithin Chand
Good one
Ajay Nagar 7Ajay Nagar 7
Useful Info...
Ryan ShoutRyan Shout
Nice find! Thanks for sharing the clear explanation Prabhjot!
allan31allan31
I really need your help. I wrote the same example provided by Salesforce, made the correction you suggested, but the subscribe method does nothing at all. It does not even output an error to me or it is catched by an exception. I know my event name is right because I have the same component as an aura and it subscibes to it without any problem. Im using an event in a Managed package, so I had to use the "namespace__" before the api name of the object. I did exactly the same in the Aura and there it woks. Could you guys give any clue about what could be the issue? 
Bellow is the code
 
handleSubscription() {
    console.log("LOG");
    const messageCallback = response => {
      console.log("New message received : ", JSON.stringify(response));
    };

    subscribe(
      "/event/MYNAMESPACE__MYCUSTOMEVENTNAME__e",
      -1,
      messageCallback
    )
      .then(response => {
        console.log(
          "Successfully subscribed to : ",
          JSON.stringify(response.channel)
        );
      })
      .catch(error => {
        console.log(error);
      });
  }

When I click in a button that has onclick={handleSubscription} I only receive the console output "LOG".
User-added image
allan31allan31
After few tests I finally discovered the problem. I have two components in my home page that subscribes to a Platform Event. I removed one and my code worked without any problems. Is this a Limitation of the API? 
One of the components is a Aura component that subscribes to a Platform Event 1. The Second component is a LWC that subscibes to a Platform Event 2. I removed the Aura from the page, then the button that subscribes to the Platform Event 2 worked wthout any changes. 
Prabhjot Singh 27Prabhjot Singh 27
Hi Allan , this should not happen because I am using to component on same page and when I am publishing both are able to show the subscription json response only difference is in my case both are lwc components. 
allan31allan31
I opened a issue on Github for them to check this issue.
https://github.com/salesforce/lwc/issues/1618

For now Im just not leaving both components on the same lightning page. I also did a test where I have two Aura components subscribing to two different Platform Events and they work perfectly like you said @Prabhjot Singh 27. The issue happens only when I have one Aura and one LWC.
Also, there is another weird behaviors happening. When I load a page which has an Aura component with empApi and then move to another lightning page that has a LWC using empApi, this page throws an exception. If I reload this lightning page the error is gone.

 
Prabhjot Singh 27Prabhjot Singh 27
@allan31 can you tell me the exception this is quite weird . I will also try using both aura and LWC together quite interesting .  
allan31allan31
There are two scenarios that I mapped. Try to simulate them in your side.

Scenario 1:
Place one Aura in a Lightning Page that subscribe to an Event A
Place one LWC in the same Lightning Page that subscribes to an Event B.
Result: The LWC subscribe will not work and it will also not thrown any exception if you put a .catch(error => { console.log(error); }) in the promisse.

Scenario 2:
Place one Aura in a Lightning Page A that subscribe to a Platform Event 1
Place one LWC in a Lightning Page B in the same Lightning APP that subscribe to a Platform Event 2
Go to Lightning Page A, wait the Aura to subscribe to the Platform Event 1
Click on the Lightning Page B and the error thrown will be the following
User-added image
Reload the page with Ctrl + R and the error is gone and the LWC will subscribe to the Platform Event 2
Nadim Shaikh 123Nadim Shaikh 123

Prabhjot Singh  - You are a genious.. you helped complete my IOT project.. thank you
Prabhjot Singh 27Prabhjot Singh 27
@Nadim I am glad it was helpful for you alway welcome. Would like to learn more about that IOT project from you let's connect some day. 
Prabhjot Singh 27Prabhjot Singh 27
In the question it self I proposed the correct way to subscribe the event in lwc which by making small change in messageCallback method. 
const messageCallback = (response) => {
        console.log('New message received : ', JSON.stringify(response));
        this.payload = JSON.stringify(response);
        console.log('this.payload: ' + this.payload);
        // Response contains the payload of the new message received
    };

 
This was selected as the best answer
Arne-Per Heurberg 2Arne-Per Heurberg 2
@allan31 did you ever discover the issue?

@Prabhjot - I was hoping your solution would solve the issue but I get the same error as @allan31
allan31allan31
If anyone else has the same issue as I had, please, describe the problem in this Github Issue https://github.com/salesforce/lwc/issues/1618
Salesforce is already aware of it and it is trying to understand.
Prabhjot Singh 27Prabhjot Singh 27
@Arne yes it is working when we have more than one lwc component in same app or when we are working with Aura components but when we have one aura and one LWC then issue still exists . just have look into the github link that @allan has shared for more details. 
Liron CohenLiron Cohen
Thanks!. almost 2H I'm trying to understand why I cannot subscribe to event from LWC until I found here the issue.
To bad SF does not correct their documentation...
Brian CBrian C
@Prabhjot Singh 27 Thank you so very much! You solved a problem I spent hours trying to figure out.