Can't set peerJS custom client id using socket.io client id in react useEffect

72 Views Asked by At

I implemented a custom PeerServer in my server.js file along with socket.io server in express as mentioned here. Both are served in separate server. I want to set the peer id with the provided id given by the socket.io server in my useEffect function where I initialized the socket client.

Here's my useEffect function.

useEffect(() => {
  const newSocket = io('http://localhost:8080');
  setSocket(newSocket);
  const newPeer = new Peer(newSocket?.id, {
    host: 'localhost',
    port: 9000,
    path: '/',
  });
  setPeer(newPeer);
  return () => newSocket.close();
}, []);

Here is the server implementation for socket.io and peer.

const http = require('http');
const express = require('express');
const { Server } = require('socket.io');
const { PeerServer } = require('peer');
const { fetchData } = require('./utils');

const port = process.env.PORT || 8080;

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: ['http://localhost:3000'],
  },
});
const peerServer = new PeerServer({
  port: 9000,
  path: '/',
});
app.get('/', (req, res) => {
  res.send({ title: 'user connected' });
});
// ...
// socket.io events
// ...
server.listen(port, () => {
  console.log(`Server running at port: ${port}`);
});

Whenever the app mounts, the socket.id becomes undefined and causes peer id to be generated by the peerServer instead of being the same as socket.id.

I tried to use two different useEffect functions but that didn't solve the problem. Any help would be greatly appreciated.

1

There are 1 best solutions below

0
Nazrul Chowdhury On BEST ANSWER

You can listen for the 'connect' event on the socket, which will be triggered once the connection is established. Try something like this,

useEffect(() => {
  const newSocket = io('http://localhost:8080');
  setSocket(newSocket);

  // wait for the 'connect' event before setting up the Peer with socket.id
  newSocket.on('connect', () => {
    const newPeer = new Peer(newSocket.id, {
      host: 'localhost',
      port: 9000,
      path: '/',
    });
    setPeer(newPeer);
  });

  return () => newSocket.close();
}, []);