How to run code directly after user login

Sorry for perhaps a stupid question but I am at a loss. I need a way to reliably obtain the email address of logged in user. I can get that with the following Velo code in masterPage.js :

import wixUsers from 'wix-users';

$w.onReady(function () {
    console.log('ready ' + Date.now());
    wixUsers.currentUser.getEmail().then( (email) => {
        console.log('hura email ' + email);
    });
});

This however works only if user clicks through a different page after log in. I can’t get it to work directly after user logs in because the onReady part is not executed. Login works in a popup / overlay window which doesn’t seem to refresh the original page from which the user decided to log in and therefore doesn’t execute the onReady function.

Is there any other function / event I could listen to while using the default login functionality without having to create my own login?

This could work for you…

import wixUsers from 'wix-users';

wixUsers.onLogin( (user) => {
 let userId = user.id;           
 let isLoggedIn = user.loggedIn; 
 let userRole = user.role;      

    console.log(userId)
    console.log(isLoggedIn)
    console.log(userRole)

    start_myFunction();
});

start_myFunction(){
 //your function here.....
}

Thank you very much Dima, this has forced me to give this function another try and finally solved my problem.

I haven’t explained the problem properly but in the end I managed to make it work after giving wixUsers.onLogin another try and implementing also an interval to look for changes.

Essentially I wanted to capture the email on a specific checkout page so that it can be then used by javascript added as the site-wide Settings->Custom Code.

So my solution was to use onReady to write user’s email to a hidden input field added on this checkout page, then use the onLogin function to write the email after login if it happens only on the checkout page and I have interval in my custom code to check whether the hidden input has empty value or not.

No problem, good luck & happy coding. :wink: