Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
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!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This made it work as I wanted:

  this[connection].onclose = evt => {
  this[connection] = null;
  console.log('closed')
  setTimeout(this._connectSocketStreams(['!ticker@arr']), 1000)};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda