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?
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/
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);
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With