Search code examples
jqueryvelo

Repeat "If" query consequently in jQuery


I would like to repeat an "If" query permanently to retrieve a piece of information and perform an action accordingly.

This should be used to display content only when a user is logged in. Currently the query happens once as soon as the page is loaded. The problem is that when a user logs in after the page is loaded, the content does not appear and the page has to be reloaded. This is my current code:

import wixUsers from 'wix-users';
   
$w.onReady( () => {
if (wixUsers.currentUser.loggedIn) {
$w('#html1').show();
$w('#button17').show();
$w('#box9').hide();
$w('#button29').show();

}
else {
$w('#html1').hide();
$w('#button17').show();
$w('#box9').show();
$w('#button29').hide();

}
});

How is it possible to always check this? Probably the solution for this is relatively simple, but I don't know much about jQuery. I appreciate any support!


Solution

  • If you want code to run after successful log-in then try wixUsers.onLogin (this needs to run inside onReady function).

    import wixUsers from 'wix-users';
        
    wixUsers.onLogin((user) => {
      let userId = user.id;
      let isLoggedIn = user.loggedIn;
      let userRole = user.role;
    } );
    

    You should be able to integrate the code snippet into your code by adding the following:

    import wixUsers from 'wix-users';
    
    function toggleLoginState(isLoggedIn) {
        if (isLoggedIn) {
            $w('#html1').show();
            $w('#button17').show();
            $w('#box9').hide();
            $w('#button29').show();
    
        }
        else {
            $w('#html1').hide();
            $w('#button17').show();
            $w('#box9').show();
            $w('#button29').hide();
    
        }
    }
    
    $w.onReady(() => {
        toggleLoginState(wixUsers.currentUser.loggedIn); // Set default state once page has finished loadading.
    
        wixUsers.onLogin((user) => {
            toggleLoginState(user.loggedIn); // This should always be true.
        });
    });
    

    More details can be found in the documentation https://www.wix.com/velo/reference/wix-users/onlogin