Search code examples
javascriptreactjswebsocket

Reconnect WebSocket in react js


The web socket server restarts on a certain time and I want my react front-end app restarts the connection each time.

this peace of code works fine but only once. I want it reconnect every time connection lost :

  _connectSocketStreams(streams) {
streams = streams.join('/');
let connection = btoa(streams);
const { BASE_WSS_PATH } = wssPath;
this[connection] = new WebSocket(`${BASE_WSS_PATH}/!ticker`);
this[connection].onmessage = evt => { 
    let ticker = this._getTickerBySymbol(JSON.parse(evt.data))
    this.props.dispatch({
        type: 'UPDATE_MARKET_PAIRS',
        data: ticker
    })
    !this.props.active_market.market && this._UsdtActive('USDT')
    this.setState({
        isLoaded: true
    })
}
this[connection].onerror = evt => {
    console.error(evt);
}
this[connection].onclose = evt => {
  this[connection] = null;
  console.log('closed')
  this[connection] = new WebSocket(`${BASE_WSS_PATH}/!ticker`);
  this[connection].onmessage = evt => {
    let ticker = this._getTickerBySymbol(JSON.parse(evt.data))
    this.props.dispatch({
      type: 'UPDATE_MARKET_PAIRS',
      data: ticker
    })
    !this.props.active_market.market && this._handleTabClick('USDT')
    this.setState({
      isLoaded: true
    })
  }

}; }

im using it in a class component constructor this will get the data stream and shows it in a table.

I tried to pass _connectSocketStreams to .onclose event: // setTimeout(this._connectSocketStreams(streams), 1000) but I got this error:

TypeError: streams.join is not a function

even tho I think its the right way to do it. Im so confused!


Solution

  • This made it work as I wanted:

      this[connection].onclose = evt => {
      this[connection] = null;
      console.log('closed')
      setTimeout(this._connectSocketStreams(['!ticker@arr']), 1000)};