Hi there,
beginner Corvid/Javascript user here.
I wrote some code for the front end that searches for a user in a database and calculates his user level based on the number of payments he has made and the time that has passed since his purchase.
Anyway, I defined all my helper functions and tested them but when I call the main function in my $w.onReady() function it only returnss “undefined”. I think I made a mistake returning the promise userLevel from the function returnUserLevel().
Hope someone can point me in the right direction.
// Imports---------------
import wixUsers from 'wix-users';
import wixData from 'wix-data';
// Constants-------------
let currentUserID = wixUsers.currentUser.id;
// Functions-------------
$w.onReady(function () {
returnUserLevel(currentUserID).then(level => {
console.log(level);
})
});
function returnUserLevel (idToCheck) { // Function to return the current user level
wixData.query("planEvents") // query planEvents
.eq("userID", idToCheck) // search for the current user ID
.find()
.then ( (results) => {
if (results.items.length > 0){ //if there is an database object with the currentUserID
let maxUserLevel = results.items[0].maxUserLevel; // extract all relevant information from the object
let currentPlanValidFrom = results.items[0].currentPlanValidFrom;
let currentPlanValidFor =results.items[0].currentPlanValidFor;
let today = new Date();
let passedMonths = monthDiff(currentPlanValidFrom, today);
let userLevel = maxUserLevel - (currentPlanValidFor - passedMonths);
return userLevel
} else {
console.log("The current user is not in the database!");
return 0;
}
})
.catch ((err) => {
let errorMsg = err
console.log(errorMsg)
})
}
function monthDiff(d1, d2) { // Function calculate the passed months since purchase of the plan
let months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months < 0 ? 0 : months+1;
}
function unlockLevels(userLevel) { // Function to unlock the different user elements on the page.
if (userLevel >= 1) {
$w('#level1').show();
$w('#placeholder1').hide();
}
if (userLevel >= 2) {
$w('#level2').show();
$w('#placeholder2').hide();
}
}