Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!