Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);

I am using socket.io and getting this error:

throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
^

TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type function. Received undefined

I am making a controller for the callbacks on the socket, this is how it looks:

const { onDisconnect } = require('./app/controllers/socket');

/*
...
*/

io.on('connection', (socket) => {
    socket.on('disconnect', onDisconnect(socket));
});

I get the error right on the "onDisconect" function. However if I declare the function like this, it works:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

io.on('connection', (socket) => {
    socket.on('disconnect', () => {
        console.log(`${socket.id} disconnected`);
    });
});

I have the "onDisconect" function on another script, which contains this:

const onDisconnect = (socket) => {
    console.log(`${socket.id} disconnected`);
}

module.exports = { onDisconnect };

>Solution :

That’s because you’re calling onDisconnect(), which returns undefined, which is not a function. You have two options:

  1. Simply change socket.on("disconnect", onDisconnect(socket)) to socket.on("disconnect", onDisconnect)
  2. Return a function in onDisconnect:
function onDisconnect(socket) {
  return () => {
    console.log(`${socket.id} disconnected`);
  };
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading