Search code examples
javascriptvelo

What does (wixUsers && wixUsers.currentUser && wixUsers.currentUser.id) mean in Wix code?


I am trying to build a custom login and came across this code that could be helpful, but I'm not sure if I completely understand it. I'm going to try to explain it and hopefully, someone will tell me if I'm on the right track or they'll correct me. I'm still relatively new to programming (and definitely apis) so keep that in mind.

First, I'll break it down. So wixUsers imports information about the different types of users. From the documentation, I see there are three types of users: visitors (users who are not logged in), a member (user who is logged in), and admin.

currentUser gets the object containing information about the user currently viewing the site.

id gets the unique id of the user.

So my interpretation of the if statement is that if there is a user and the current user has an id.

Then if that is true, it takes the id of the current user and stores it in the contactInfo object of the key _id. It is my understanding that when you use wixUsers.currentUser.id at login, it's a random id that's not the one that's associated with the contactInfo that's in the database collection that's created when one registers??? Thanks in advance!

if (wixUsers && wixUsers.currentUser && wixUsers.currentUser.id) {
                userData.contactInfo._id = wixUsers.currentUser.id;
                await wixData.insert("MemberProfileDatabase", userData.contactInfo);
                wixLocation.to('/account/my-account/')
            }

Solution

  • You've pretty much got it - the if statement is there to see if

    • wixUsers exists, in which case it's assumed to be an object, and then checks:
    • wixUsers.currentUser exists, in which case it's assumed to be an object, and then checks (* wixUsers.currentUser.id exists

    You can't just check wixUsers.currentUser.id alone to start with because if wixUsers is undefined, or if currentUser is undefined (or null), an error will be thrown.

    That said, in newer environments (or if the code is transpiled), the syntax is made much easier with optional chaining:

    if (wixUsers?.currentUser?.id) {
    

    which is equivalent to the original if check.

    If the id is found, it's assigned to the contactInfo and saved to the database.

    Though, I'd prefer to extract the ID to start with, rather than repeating wixUsers.currentUser.id:

    const id = wixUsers?.currentUser.id;
    if (id) {
      userData.contactInfo._id = id;
      // etc