I've looked everywhere but I couldn't find a working answer for my problem - in Wix Velo I'd like to hide the element #image1 from every site member except for members who have the role Gardener among their roles. I have a code, but it doesn't work anymore if the member has other roles aside from the Gardener role assigned to them (for example, if the member has both Gardener role and Florist role).
I think the "firstRole" thing is the problem here, but even if it is, I have no idea how to fix it. What would the solution be? Thank you in advance!
I know that this works when a member only has one role assigned to them (Gardener):
import wixUsers from 'wix-users';
$w.onReady(function () {
var roleName;
let currentUser = wixUsers.currentUser;
currentUser.getRoles()
.then((roles) => {
var firstRole = roles[0];
roleName = firstRole.name;
if (roleName === 'Gardener') {
$w('#image1').show();
} else {
$w('#image1').hide();
}
})
})
Your code issue arises because it only checks a user's first role. If "Gardener" isn't first among multiple roles, the user isn't recognized as a Gardener. Modify the code to check if "Gardener" is present in any of the user's roles.
Try this:
import wixUsers from 'wix-users';
$w.onReady(function () {
let currentUser = wixUsers.currentUser;
currentUser.getRoles()
.then((roles) => {
// Check if any of the roles is 'Gardener'
const isGardener = roles.some(role => role.name === 'Gardener');
if (isGardener) {
$w('#image1').show();
} else {
$w('#image1').hide();
}
});
});
Here's what the modified code does:
Uses the Array.prototype.some
method to check if any role in the user's roles array has the name "Gardener".
If isGardener is true, it shows #image1
. If it's false, #image1
is hidden.
This approach ensures that even if "Gardener" is not the first role in the list, as long as the user has it among their roles, #image1
will be displayed.