Reputation: 33
I want to create a room for a chat app I'm building in node and vue js. Unfortunately I keep getting error .join is not a function for socket .io. I understand its a server sided function so I am using it in server side only yet the problem still persists. All the other functions like .emit() works fine.
Here's my Index.js
let io = require('./socket')
let server = app.listen(8000)
io = io.init(server)
io.on('connection', socket => {
console.log('Client Connected')
})
Ive taken this piece of code from Udemy's Maxmilian's Node js master course.
Here's my socket.js where I export the socket functions. Essentially I have created a sharing instance to work with socket in other files.
socket.js
let io
module.exports = {
init: httpServer => {
io = require('socket.io')(httpServer, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
}
})
return io
},
getIO: () => {
if(!io){
console.log('Socket is not Initialized')
}
return io
}
}
Last but not least heres my customer_controller.js where I try to join the socket.join() customer_controller.js
exports.getMessages = async(req, res, next) => {
try {
let messages = await Message.find({
users: [ req.user.email, '[email protected]' ] })
.populate('sender')
.sort({"updatedAt": 1})
io.getIO().join(req.user.email)
res.json(messages)
} catch(err) {
console.log(err)
}
}
Here's my detailed error!
TypeError: io.getIO(...).join is not a function
Upvotes: 0
Views: 1393
Reputation: 33
If anybody wanted to know the solution. It should be:
io.getIO(socket => {
socket.join(req.user.email)
})
and not
io.getIO().join(req.user.email)
since socket has the function called .join() not io. Here's the docs. See carefully Ive missed several times. Although I'm still facing a problem regarding console logging socket.rooms
When I do
console.log(socket.rooms)
in customer_controller.js, it returns nothing not even an error. But when I do it in index.js file like so:
index.js
io.on('connection', socket => {
console.log(socket.rooms)
})
It returns a set. If anyone has more efficient way to deal with this please post your answer. Ill accept it as solution. Thank you
Upvotes: 1