Login Code Doesn't Always Run

My login works, but the problem I’m having is that it only runs once and not again unless the page is manually refreshed.

For example, once you load the homepage for the first time the code works.
Then once you logout the code still works as should.
However if you try to login again the code doesn’t work.

So it seems as though the code only runs once and this is a problem.

Here is the code:

import wixUsers from ‘wix-users’;
import wixLocation from ‘wix-location’;

$w.onReady( function () {
//$w(“#button9”).hide();

let user = wixUsers.currentUser;

let userId = user.id;
let isLoggedIn = user.loggedIn; // “let” the variable “isLoggedIn” represent that the current “user” is “.loggedIn”

let userRole;
let userEmail;

user.getEmail() 
    .then((email) => { 
        userEmail = email; 
        user.getRoles() 
            .then((roles) => { 
                userRole = roles[0].name; 

            }) 
    }) 

if (isLoggedIn) {
wixLocation.to(“/login”);
$w(“#button9”).show();
} else {
$w(“#button9”).hide();
}

});

I’ve also taken screenshots of the process. I want the second “premium” button that is shown in the first screenshot to reappear once the user logs in again but it doesn’t. Please help.

SOLVED: The fix was that I had to write some basic code for the login on the page panel as well. Once I did this it seemed to keep my code consistent.

Here is the code I used if anyone needs it as a reference for their login issue:

SITE:
import wixUsers from ‘wix-users’;
import wixLocation from ‘wix-location’;

$w.onReady( function () {
//$w(“#button9”).hide();

let user = wixUsers.currentUser;

let userId = user.id;
let isLoggedIn = user.loggedIn; // “let” the variable “isLoggedIn” represent that the current “user” is “.loggedIn”

let userRole;
let userEmail;

user.getEmail() 
    .then((email) => { 
        userEmail = email; 
        user.getRoles() 
            .then((roles) => { 
                userRole = roles[0].name; 

            }) 
    }) 

if (isLoggedIn) {
wixLocation.to(“/login”);
$w(“#button9”).show();
} else {
$w(“#button9”).hide();
}

});

PAGE:

import wixUsers from ‘wix-users’;

wixUsers.onLogin( (user) => {

let isLoggedIn = user.loggedIn; // true

$w(“#button9”).show();
} );

2 Likes