Ad

Call React Function Inside Anonymous Function

- 1 answer

I have a function inside a react component like this

addItem: function(data) {
    console.log(data)
    var oldMessages = this.state.messages;
    oldMessages.push({id: data.uid, content: data});

    this.setState({messages: oldMessages});
    this.scrollAndSetTimestamps()
    this.updateCount()
  },
componentDidMount: function() {
this.loadLatestMessages();
var socket = new SockJS('http://127.0.0.1:8080/stomp');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
  // subscribe to the /room.uid endpoint
  stompClient.subscribe("/room.1247016", function(data) {
      var message = data.body;
      console.log("Received: "+message);
      this.addItem();
  });
 });
},

turns out that the addItem is not found when a message arrives. How can I call a react method inside an anon function?

Ad

Answer

The simplest solution is to store correct reference to this context in some variable:

var self = this;
stompClient.connect({}, function(frame) {
    stompClient.subscribe("/room.1247016", function(data) {
        var message = data.body;
        self.addItem();
    });
});

You could also use Function.prototype.bind, but this is not very readable:

stompClient.connect({}, function(frame) {
    stompClient.subscribe("/room.1247016", function(data) {
        var message = data.body;
        this.addItem();
    }.bind(this));
}.bind(this));

Finally, you could also go with ES2015 arrow functions which hold lexical scope:

stompClient.connect({}, frame => {
    stompClient.subscribe("/room.1247016", data => {
        var message = data.body;
        this.addItem();
    });
});
Ad
source: stackoverflow.com
Ad