Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access component method in React from a WebSocket callback

I have a problem with Javascript and React. I want to change a components state based on push messages from a WebSocket.

My problem is that I do not know how to call the the function handlePushMessage from the WebSocket callback. Here is the code:

const MainPage = React.createClass({
    ...
    componentDidMount: function() {    
        var connection = new WebSocket('ws://localhost:12345');
        connection.onmessage = function (e) {
            var jsonData = JSON.parse(e.data);
            handlePushMessage(jsonData);
        };
    },

    handlePushMessage: function(data) {
        ...
    }
}

I have tried different syntaxes for specifying that function and I tried accessing the function via this. However nothing has helped. Any ideas?

like image 328
jsf Avatar asked Mar 22 '26 05:03

jsf


2 Answers

Try using that (save this before the callback):

const MainPage = React.createClass({
    ...
    componentDidMount: function() {    
        const connection = new WebSocket('ws://localhost:12345');
        const that = this;
        connection.onmessage = function (e) {
            const jsonData = JSON.parse(e.data);
            that.handlePushMessage(jsonData);
        };
    },

    handlePushMessage: function(data) {
        ...
    }
}

Explanation: while in the callback, this refers to the connection object and not to the class you created.

A working jsFiddle example: https://jsfiddle.net/esnuxz81/3/

like image 198
Technotronic Avatar answered Mar 23 '26 19:03

Technotronic


This should work too:

const MainPage = React.createClass({
    ...
    componentDidMount: function() {    
        var connection = new WebSocket('ws://localhost:12345');
        connection.onmessage = this.handlePushMessage;
    },

    handlePushMessage: function(e) {
        var jsonData = JSON.parse(e.data);
        ...
    }
}
like image 35
romseguy Avatar answered Mar 23 '26 17:03

romseguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!