1

Following advice from this question on forcing a component to update, I wrote the following code to update the component when my socket connection receives a broadcast.

constructor(props) {
    super(props)
    this.state = { key: 0 };
}   

componentWillMount(){
    const socket = io()

    socket.on('data', function(data) {

        // Do stuff with the data

        this.setState({ key: Math.random() })
    })
}

But I get the error

Uncaught TypeError: this.setState is not a function

I understand that this is because this is referring to something different when It's inside the socket.on() function but I don't know a way around it.

I also tried

constructor(props) {
    super(props)
    this.state = { key: 0 };
    this.update = this.update.bind(this);
}

componentWillMount(){
    const socket = io()

    socket.on('data', function(data) {

        // Do stuff with the data

        update()
    })
}

update(){
    this.setState({ key: Math.random() })
}

But then I get the error

Uncaught ReferenceError: update is not defined

Does anyone have a better way to update my component or a fix for my current implementation?

Charlie
  • 530
  • 10
  • 26

1 Answers1

1

You loose the context of this unless you do it as an arrow function:

socket.on('data', (data) => {

Also as you are using a class component you don't need that setState trick you can do this.forceUpdate().

Dominic
  • 62,658
  • 20
  • 139
  • 163