Search code examples
salesforcelwc

lwc - how to call a function from within an lwc callback


Havent been able to reconcile this challenge to the docs :/ Hoping someone can point out to me why when this lwc renders (successfully) and it receives an event via its empApi subscription it throws a 'handleGoNext is not defined' runtime error. I appreciate the function is not visible, but I'm not able to construct things such that a resulting function call is able to be made successfully. Calling this.handleGoNext() doesnt work either. Any pointers would be most appreciated!

handleGoNext(){
    // *** this is the logic Im hoping to call ***
};


// Initializes the component
connectedCallback() {
   if(this.subscription = {}){ 
        
        // Callback invoked whenever a new event message is received
        
        const messageCallback = function (response) {
            handleGoNext(); // *** THIS IS THE CALL THAT BREAKS THINGS ***
        };
        
        // Invoke subscribe method of empApi. Pass reference to messageCallback
        subscribe(this.channelName, -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;
        });
    }
}

Solution

  • what happens when you do subscribe(this.channelName, -1, this.handleGoNext)?

    Here's my function from around Easter time, didn't check recently if it still works.

    
    isSubscribed = false;
    subscription = {};
    replayId;
    
    @track data = [];
    
    subscribe(id) {
            const handleMessage = (response) => {
                let val = Object.assign({}, response.data.event, response.data.payload);
                this.replayId = Math.max(this.replayId ?? 0, val.replayId);
    
                /*  do not use this.data.push(val);
                    it doesn't play well with datatable. Use the spread operator or JSON.parse/JSON.stringify trick.
                    Plus we want new rows to be added on top of the list.`
                */
                this.data = [val, ...this.data];
            };
    
            subscribe(this.channel, id, handleMessage).then((response) => {
                this.subscription = response;
                this.isSubscribed = true;
            });
        }