Hi –
I am trying to set up code that allows members to log into a unique profile through a dynamic page, according to their e-mail. Simultaneously, if they are a new user, with no prior profile, I need it to create a new entry into my database. I can do each of these separately, but am having trouble combining them. The following code is not working.
Any thoughts would be HUGELY helpful. Thanks.
import wixUsers from 'wix-users';
import wixLocation from 'wix-location';
import wixData from 'wix-data'
import wixWindow from 'wix-window'
$w.onReady(() => {
let user = wixUsers.currentUser;
setLoginSignUpButton(wixUsers.currentUser);
});
function setLoginSignUpButton(user) {
let loggedIn = user.loggedIn;
let button = $w('#customLoginButton');
if (loggedIn) {
button.label = 'Logout';
createNewUserIfNoneExists(user);
}
button.onClick(() => {
if (loggedIn) {
wixUsers.logout();
button.label = 'Login or Sign Up';
} else {
wixUsers.promptLogin();
(user) => {
let userId = user.id;
let userRole = user.role;
user.getEmail()
.then( (email) => {
let userEmail = email;
wixLocation.to('/Members/' + userEmail);
setProfileButton(user);
});
}}
function createNewUserIfNoneExists(user) {
let userId = user.id,
userRole = user.role;
if (userRole !== 'Visitor') {
wixData.query('Member_Database')
.eq('_owner', userId)
.find()
.then((result) => {
if (result.items.length === 0) {
let insert = {
'reports': 0
};
wixData.insert('Member_Database', insert)
.then((results) => {
console.log(results);
console.log('New user added');
wixWindow.openLightbox('Set Profile');
});
}
});
console.log('Hi user!');
} else {
console.log('Hi visitor!');
}
}
function setProfileButton(userId) {
wixData.query('users')
.eq('_owner', userId)
.find()
.then((result) => {
let button = $w('#button3');
if (result.items.length === 0) {
button.label = 'Visitor';
} else {
console.log('Profile button' + result.items[0].username);
button.label = result.items[0].username;
}
});