NewScientists
NewScientists

Reputation: 1262

Socket.io unable to access handshake query params inside event handlers

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.

Upvotes: 0

Views: 384

Answers (2)

Ruslan Kabalin
Ruslan Kabalin

Reputation: 6908

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));
  ...
}

Upvotes: 0

ghostscypher
ghostscypher

Reputation: 3

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.

Upvotes: 0

Related Questions