[HELP!] Change what button does depending if user is logged in

llo!

Im trying to make a button “button38” change what it does depending if a user is logged in or not

If the user is logged in, I want the button to take them to their member profile ( /members/ ${ wixUsers . currentUser . id })

If the user is not logged in, I want the button to take them to the standard wix signup/login screen - I havn’t designed and dont intend to use a custom login/signup page, im happy to use what wix provides as standard.

If they sign up as a new member, I want the data to go to the “members” database in my content manager

After they sign up or log in, I want them automatically redirected to their member profile

This is my first time ever using the API reference, and im trying to cannibalise code that was written for me in the old " wixUsers" API to update it to the new " wix-members" API, as the function seems to have stopped working correctly

(when a user registers, it redirects them to their user profile URL however displays a 404 error. I know it is the correct URL as all it takes to access their profile is refreshing the page - I believe the error lies in that the user profile page is loading before their data has been submitted to the content manager - therefore meaning the custom user URL is being created slightly after the page is redirecting them to it… but I could be very wrong!)

I believe I have the start correct in that the logic is:
If the user is logged in,
change the button “button1”
to redirect to their profile page

I also believe the end is correct in that the logic is:
when the user logs in
send them to their profile page

my problem, and the part which I am frustratingly not understanding is the middle section. The section which actually deals with the logic of:
if the user is not logged in
send them to the login/signup page
and submit the signup data to the “members” database


import wixData from 'wix-data';
import wixLocation from 'wix-location';
import { authentication, currentMember } from 'wix-members';
const loggedIn = authentication.loggedIn();

  if (loggedIn) {
    const loggedInMember = await currentMember.getMember()
    console.log('Member is logged in:', loggedInMember);
    const memberId = loggedInMember._id;
    const contactId = loggedInMember.contactId;
$w("#button38").onClick(function () {
wixLocation.to(`/members/${wixUsers.currentUser.id}`) 
}); 

  } else {
authentication.register(email, password)
  .then((registrationResult) => {

    return wixData.query("Members")
          .eq("_id", userId)
          .find();
     });
    
    const status = registrationResult.status;
authentication.login(_id, email)

wixData.insert("Members", toInsert)
          .then((item) => {
  });
  

authentication.onLogin(async (member) => {
  const loggedInMember = await member.getMember();
  const memberId = loggedInMember._id;
  wixLocation.to(`/members/${wixUsers.currentUser.id}`) 
});

I apologise if the code is a mess and makes no sense.

for some reason I have a lot less red error lines when the code is on my actual page then are appearing in the code above

However, I am a complete newbie and am only trying to cannibalise code from the old API which was given to me, and the current API reference,

for reference, the old code (which mostly works 100%, but is written in an outdated API) is:


import wixUsers from 'wix-users';
import wixData from 'wix-data';
import wixLocation from 'wix-location';

export function button38_click(event) { 
  // user is logged in
  if(wixUsers.currentUser.loggedIn) {
    // go to profile
    Promise.all( [ wixLocation.to(`/members/${wixUsers.currentUser.id}`) ] )
  }
  // user is logged out
  else {
    let userId;
    let userEmail;
  
    // prompt the user to log in 
    wixUsers.promptLogin( {"mode": "log in"} )
      .then( (user) => {
        userId = user.id;
        return user.getEmail();
      } )
      .then( (email) => {
        // check if there is an item for the user in the collection
        userEmail = email;
        return wixData.query("Members")
          .eq("_id", userId)
          .find();
      } )
      .then( (results) => {
        // if an item for the user is not found
        if (results.items.length === 0) {
          // create an item
          const toInsert = {
            "_id": userId,
            "email": userEmail
          };

          // add the item to the collection
          wixData.insert("Members", toInsert)
          
          
          // go to profile
          .then((item) => {
wixLocation.to(`/members/${wixUsers.currentUser.id}`);
})

            .catch( (err) => {
              console.log(err);
             

            } );
          
        }

        // go to profile
       wixLocation.to(`/members/${wixUsers.currentUser.id}`);
      } )

  }
}

I’m sure this is not difficult logic for someone who knows what they are doing! and I appreciate any help that you can share about how to convert this to the new API, and point out the errors which I have made in my attempt! (I dont understand any of what it is doing - its just copy and paste from the API reference examples)

Thankyou so much!

Hey, firstly you need to call the APIs inside the onReady (otherwise it might not work on the live site).
Also you don’t need to get all the member data, you can use LoggedIn function of the Wix Members API.
To direct to the login/signup screen you can use the promptLogin function.

So the end code will be something like:

import { authentication } from 'wix-members';
import wixLocation from 'wix-location';
$w.onReady(function () {
const isLoggedIn = authentication.loggedIn();
    if (isLoggedIn) {
    //get the user ID from the getMember function and redirect with Wix Location API
    } else {
       //prompt login
    }
});

I use similar approach on my own site to display different content depending is the user is logged in or not (feel free to check the page here).

Thankyou so much!!Will check out your site now :slightly_smiling_face: