0

So now I'm storing info when user submits login form.

io.on('connection', (socket) => {

let userInfo; 

    socket.on('login', (data) => {
        userInfo = data;
        console.log(userInfo); // {username: 'testusername'}
    });

    socket.on('lobby-left', (userInfo) => {
        console.log(userInfo); // { } 
    });

The problem is that in lobby-left I don't get any info from the variable anymore. I get empty brackets { }. How can I reuse the variable so I can use the login info in all functions ?

7
  • @AshayMandwarya TY for suggestion, but still getting empty brackets. Commented Jan 15, 2019 at 19:26
  • You have created a closure to hold userInfo, and then your overriding it with your callback params. Just do -> socket.on('lobby-left', () => { and let your closure work. Commented Jan 15, 2019 at 19:31
  • @Keith I even deleted the paremeter but then I get undefined Commented Jan 15, 2019 at 19:39
  • If login in fired before lobby-left, then you shouldn't be getting undefined. This is basic Javascript closures, and is how I use them with socket.io without issues. There is maybe something else were missing here. Commented Jan 15, 2019 at 19:41
  • @Keith Well at first I need to login to website to use any other functions. So it's fired at the begining. Commented Jan 15, 2019 at 19:42

1 Answer 1

1

You need assign it to userInfo

let userInfo; 

socket.on('login', (data) => {
    userInfo = data;
    console.log(userInfo); // {username: 'testusername'}
});

socket.on('lobby-left', (userInfoParam) => {
    console.log(userInfo); // { } 
});
Sign up to request clarification or add additional context in comments.

6 Comments

Still empty brackets.
You need check console.log(userInfoParam). I think event data is empty object
I need to reuse same data from login socket, not what I get from lobby-left socket. I don't want to get anything from lobby-left socket, I want to reuse same info from login socket
Update my answer. You need change lobby-left callback parametr name, because its same name with userInfo
I even deleted the paremeter but then I get undefined
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.