Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call react function inside anonymous function

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?

like image 574
Luiz E. Avatar asked Dec 10 '22 19:12

Luiz E.


1 Answers

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();
    });
});
like image 178
dfsq Avatar answered Dec 23 '22 08:12

dfsq