Monday, 11 October 2021

Reconnecting to socket channel after disconnection in react

There's various answers to this question, but either they're outdated (I don't think the "reconnect" event exist anymore?) or just doesn't work for me.

I have a ton of data that the client is waiting for from the server via socket.io sockets. It's fine until 10-15 minutes later with over 1600 results that the socket reconnects. After the reconnection happens, I do not get anymore of the data that the server emits, which I assume is because I've lost the events from the original socket connection.

I have to refresh to continue getting that data.

How do I reconnect to socket.io after every reconnection?

Client:

socket.js (context)

import { createContext } from 'react';
import io from 'socket.io-client';

export const socket = io('http://localhost:5000');

export const SocketContext = createContext();

Layout.js

import { socket, SocketContext } from '../context/socket'

function MyApp({ Component, pageProps }) {

  return <SocketContext.Provider value={socket}>
    <Layout>
      <Component {...pageProps} />
    </Layout>
  </SocketContext.Provider>
}

page (next.js)

  import { SocketContext } from '../context/socket'; 
  ...
  const socket = useContext(SocketContext);
  useEffect(() => {
    socket.emit('joined', socketChannel);
    socket.on(socketChannel, handleStream);
  }, []);

Server:

index.js (Uses fastify-socket.io)

    fastify.io.on('connection', socket => {
        socket.on('joined', (channel) => {
            socket.join(channel);
        })
    });
    redis.subscriber.on('message', (channel, message) => {
        io.to(channel).emit(channel, message);
    });


from Reconnecting to socket channel after disconnection in react

No comments:

Post a Comment