Ross Attrill
Ross Attrill

Reputation: 2702

How to respond to websocket disconnect with React

I am trying to create a WebSocket client using React. I have adapted code from https://github.com/bitlabstudio/blogpost-react-websocket-chat/blob/master/frontend/src/Chat.js to create a WebSocket listener component as follows:

class WsListen extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
        lastMessage: '',
        ws: null
      }
    }

  componentDidMount() {

    let ws = new WebSocket(URL)
    this.setState({ws: ws})

    ws.onopen = () => {
      console.log('connected')
    }

    ws.onmessage = evt => {
      console.log(evt.data)
      this.setState({lastMessage: evt.data})
    }

    ws.onclose = () => {
      console.log('disconnected')
      // automatically try to reconnect on connection loss
      this.setState({ws: new WebSocket(URL)})
    }
  }

  render() {
    return (
      <div>
        <p>Last message: {this.state.lastMessage}</p>
      </div>
      );
    };
}

This works fine for creating a connection and listening to messages. However, the logic to reconnect when the server sends a disconnect doesn't work. On the server, I can see that the client has reconnected and been registered by the server. But after the disconnection and reconnection, messages are no longer detected or responded to by the client.

Upvotes: 0

Views: 2676

Answers (1)

Egan Wolf
Egan Wolf

Reputation: 3573

Your ws no longer has onmessage function. You can create a WebSocket factory method and call it when new ws is needed.

createWebSocket = URL => {

    let ws = new WebSocket(URL);
    ws.onopen = () => {
      console.log('connected')
    }

    ws.onmessage = evt => {
      console.log(evt.data)
      this.setState({lastMessage: evt.data})
    }

    ws.onclose = () => {
      console.log('disconnected')
      // automatically try to reconnect on connection loss
      this.setState({ws: this.createWebSocket(URL)})
    }

return ws;
}

componentDidMount() {

    this.setState({ws: this.createWebSocket(URL)})

}

Upvotes: 2

Related Questions