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?
 
    