0

How can i access the initial handshake query params from within the socket.on event handler, portfolioID shows within io.on("connection")..., but inside socket.on("UPDATES")..., it is undefined.

io.on("connection", socket => {
  const { portfolioID } = socket.handshake.query;
  console.log(portfolioID); // Shows ID

  socket.on("UPDATES",() => {
    console.log(portfolioID); // Undefined ID
    ...
  });

  ...
}

The first console log works, the second returns undefined.

2 Answers 2

0

I am not entirely sure, but I think that because the second portfolioId is inside an anonymous function, the function has not captured it, or in other words the function is not aware of the existence of such a variable.

0

Your variable is not visible in the event callback function context, but you can add it as extra argument to callback by using partial function from Underscore, e.g.

io.on("connection", socket => {
  const { portfolioID } = socket.handshake.query;
  console.log(portfolioID); // Shows ID

  const callback = (portfolioID, ...args) => {
    console.log(portfolioID); // Shows ID
    console.log(args); //array of other arguments sent with event
    ...
  };

  socket.on("UPDATES", _.partial(callback, portfolioID));
  ...
}

Also, you can pass socket object entirely similar way:

io.on("connection", socket => {

  const callback = (socket, ...args) => {
    const { portfolioID } = socket.handshake.query;
    console.log(portfolioID); // Shows ID
    console.log(args); //array of other arguments sent with event
    ...
  };

  socket.on("UPDATES", _.partial(callback, socket));
  ...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.