'Socket.io: Cannot read property 'emit' of undefined
So i am trying to connect multiple users to a room where video can be shared, but I keep getting an error whenever I join a room which is Cannot read property 'emit' of undefined which is thrown for the socket.to(roomId).broadcast.emit('user-connected', userId) line. I'm not sure what is causing this, and any help would be great. Cheers.
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/', (req, res) => {
res.redirect(`/${uuidV4()}`)
})
app.get('/:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
io.on('connection', socket => {
socket.on('join-room', (roomId, userId) => {
socket.join(roomId)
socket.to(roomId).broadcast.emit('user-connected', userId)
// This line here
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId)
})
})
})
server.listen(3000)
Solution 1:[1]
If I am right, you are following Web Dev Simplified's Zoom Clone video, I was facing the same issue, but omitting the .broadcast property works fine.
Solution 2:[2]
socket.broadcast.to(roomId).emit("user-connected", userId);
It worked for me
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dc0xdx 1013 |
| Solution 2 | Tyler2P |
