Button Shows When User Logged In (I have a problem)

Hello Guys. I found a code that solves my problem but…

import wixUsers from 'wix-users';

$w.onReady(function () {
 if(!wixUsers.currentUser.loggedIn){
        $w("#button3").hide(); // content hidden if you're not logged in
    } else {
        $w("#button3").show(); // content visible if you're logged in
    }
});


As you see above, there is only one button and it says login or register.

This is the dev console.

When user logs in, hidden button does not show at first. User needs to refresh the page to see the button. Is there anyway to solve this problem without needing refreshing the page afer user logs in?

Thanks!

Hi there, wixUsers is deprecated. Use this code instead:

import { authentication } from 'wix-members-frontend';

$w.onReady(function () => {

  const isLoggedIn = authentication.loggedIn();

  if (isLoggedIn) {

    $w("#button3").show(); // Handle when member isn't logged in

  } else {

    $w("#button3").hide(); // Handle when member isn't logged in

  }
});

Hello! I tried this code but it got error and said “Expected 1 arguments, but got 2”

Thanks for your reply! Any idea how to solve this?

Solved it! Here is the correct code. Thanks! @Pratham

import { authentication } from 'wix-members-frontend';

$w.onReady(function () {
  const isLoggedIn = authentication.loggedIn();
  if (isLoggedIn) {
    $w("#button3").show(); // Handle when member is logged in
  } else {
    $w("#button3").hide(); // Handle when member isn't logged in
  }
});

1 Like

HI, this code makes the buttons show / hide correctly. However once you login the button is visible and the page needs to be refreshed to hide the button. Any ideas?

Yes, if the user logs in on the page itself then that does not refresh the page automatically, and since the above code runs on page load only, it will not fire when a user logs in or out. This happens when the page permissions are not set to members only.

So in this case, use the code below that fires whenever a user logs in or logs out.

import { authentication } from 'wix-members-frontend';

$w.onReady(function () {
  handleButtonVisibility();
});

authentication.onLogout(() => {
    handleButtonVisibility();
});

authentication.onLogin((member) => {
    handleButtonVisibility();
});

function handleButtonVisibility() {

  const isLoggedIn = authentication.loggedIn();
  if (isLoggedIn) {
    $w("#button3").show(); // Handle when member is logged in
  } else {
    $w("#button3").hide(); // Handle when member isn't logged in
  }

}
1 Like